ES6标准以前,JavaScript并无模块体系,特别是浏览器端经过<script>
引入的代码被看成脚本执行。社区中则制定了一些标准:如CommonJS、AMD、CMD,CommonJS同步加载主要用于服务端,AMD、CMD异步加载则用于浏览器端。javascript
ES6静态加载的设计思想,使得在编译时就能够肯定模块的依赖关系,以及输入、输出的变量。ES6则在语言层面上实现了模块化,取代CommonJS、AMD、CMD成为服务端和浏览器端通用的模块解决方案。(CommonJS、AMD、CMD运行时肯定依赖关系)java
this
为undefined
// example1.js
export let/var/const param1 = 'ok'
export function method1 () {}
// 先声明再导出
let/var/const param2 = 'error'
export param2
import { param1, method1 } from './example1.js'
import * as example1 from './example1.js'
example1.param1 // 'ok'
复制代码
default
// example2.js
export default val param2 = 'ok'
// example3.js
export default function foo () {}
import param2 from './example2.js'
import foo from './example3.js'
复制代码
有的模块能够不导出任何东西,他们只修改全局做用域中的对象。例如,咱们须要为Array
原型增长方法,就能够采用无绑定导入。数组
// example.js
Array.prototype.pushAll = (items) => {
// ES6数组方法的内部实现,能够写篇文章讨论下
// isArray方法实现:
// Object.prototype.toString.call(arg) === '[object Array]'
if (!Array.isArray(items)) {
throw new TypeError('参数必须是数组')
}
// 使用展开运算符
return this.push(...items)
}
// 使用时,直接import
import './example.js'
let items = []
let arr = [1, 2, 3]
items.pushAll(arr)
复制代码
默认状况下,浏览器同步加载<script>
,遇到<script>
标签就会中止渲染,执行完脚本才会继续渲染。若是遇到特别大的脚本,就会长时间白屏,用户体验不好。浏览器
<!-- 页面内嵌的脚本 -->
<script type="text/javascript"> </script>
<!-- 外部脚本 -->
<script type="text/javascript" src="./example.js"></script>
复制代码
由于以前说到浏览器同步加载<script>
标签,使用async
和defer
标签就能够异步加载。区别在于:异步
<script type="text/javascript" src="./module1.js" defer></script>
<!-- 这里面没法知道module二、module3那个先执行,由于不知道那个先加载完 -->
<script type="text/javascript" src="./module2.js" async></script>
<script type="text/javascript" src="./module3.js" async></script>
复制代码
在浏览器端使用脚本默认开启defer
属性,也就是按照引入的顺序一个一个加载,这也符合静态化的思想。async
浏览器端使用ES6模块以下:模块化
<script type='module' src='module1.js'></script>
<script type='module'>
import utils from './utils.js'
// 其余代码
</script>
复制代码
// math.js
export let val = 1
export function add () {
val++
}
// test.js
import { val, add } from './math.js'
console.log(val) // 1
add()
console.log(val) // 2
复制代码