1.前端模块化
ES Module(浏览器)
CommonJS(nodejs模块化规范)
一个文件就是一个模块
每个模块都有单独的作用域
通过 module.exports 导出成员
通过 require 函数载入模块
2.ES Module特性
通过给 script 标签添加 type = "module" 的属性,就可以,以 ES Module 的标准执行其中的js代码了。
1.ESM自动采用严格模式,忽略 'use strict'
比如不能全局范围使用this
<script type="module">
console.log(this)//undefined
</script>
2.每个 ES Module 都是运行在单独的私有作用域中
不同script标签中,let变量无法共享
3.ESM是通过CORS的方式请求外部js模块的
script标签的,src中的地址要支持cors
4.ESM的script标签,会自动延迟执行脚本(等同于script标签的defer属性)
3.ES Module导入导出
import { name, hello } from "./module.js";
console.log(name);
console.log(hello());
module.js
export var name = 'foo'
export function hello() {
return 'hello'
}
var name = 'foo'
function hello() {
return 'hello'
}
export { name, hello }
// import 可以 name as xname
// export default name,import 名字随便起
export import是引用(export的地方改变,会影响外部import),import只读的,不能修改