script 标签 <script type=“module“>

本文介绍了前端模块化的概念,重点关注ES6Module在script标签中的应用,包括如何使用`import`和`export`,以及区分方法1(在script内导入并调用)和方法2(src引入index.js)。
摘要由CSDN通过智能技术生成

module, 顾名思义就是模块化。

一开始都是社区, 前端圈的大佬们自己实现模块化, 比如seajs, nodejs使用的CommonJS规范, 以及异步模块定义 AMD,官方的ES6 Module, 同时ES6 Module也是我们目前前端工程化开发中运用最广泛的模块化规范

具体有关于前端模块化可参照下面这篇文章了​​​​​​​

聊一聊前端模块化_ikkkp_的博客-CSDN博客

在script标签中写js代码,或者使用src引入js文件时,默认不能使用module形式,即不能使用import导入文件,但是我们可以再script标签上加上type=module属性来改变方式。

//module.js
export default function test(){
  return 'test'
}
// index.js
import test from './module.js';
console.log(test())

下面通过两种方法展示js模块的引用: 

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  // 方法 1 : 引入module.js,然后在script标签里面调用
  <script type="module">
    import test from './module.js';
    console.log(test())
  </script>
 
  // 方法 2 : 直接引入index.js,使用src引入
  <script type="module" src="./index.js"></script>
 
</body>
</html>

使用方法1:要从模块导入多个名称,或者从在一个<script>标签引入多个模块

使用方法1:想要导入多个模块,就得需要多个<script>标签

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ikkkp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值