es6模块

本文介绍浏览器环境的es6模块
浏览器环境中,type=”module”自动标志这个内联或者外联脚本是一个模块。一般模块脚本建议后缀为.mjs,这也与nodejs的保持一致,nodejs中es6的模块化特性只支持.mjs后缀的文件(nodejs9+ :node –experimental-modules 1.mjs).
es6的模块特性:
1.天然自带异步特性,即自带defer,es6模块按顺序先后执行

<script type="module" src="./2.js"></script>
<script type="module">
    console.log('4.type-module.module');
</script>
<script defer>
    console.log('1.defer script');
</script>
<script>
    console.log('2.script');
</script>
<script defer src="./3.js"></script>

输出1.defer script后外链的输出2.script 后 2.js(外链js模块由于顺序靠前,也在非外链js模块前执行,所以能保证顺序)然后4.type-module.module 最后3.js.
内联script没有defer属性,设置defer属性无效,无视defer。
2.支持async,异步加载脚本,区别于defer的保证执行顺序,其谁先加载好谁先执行。
3.同一个js只会加载且执行一次
4.总是CORS跨域请求,所以非同源会报错,需要模块资源服务端配置Access-Control-Allow-Origin
5.模块脚本默认不发送cookie等。需要设置crossorigin=”use-credentials”来携带cookie。API接口会带cookie不用修改
6.天然严格模式
7.静态import和动态import:静态import在首次加载时会把全部资源都加载下来。而动态import按需加载
a).静态import

<script async type="module">
import * as a from './1.js'
</script>

b).动态import(此import非函数,返回promise)

<script>
setTimeout(() => {
    import('./1.js').then(function (a) {
        console.log('1---', a)
    });
}, 5000);
</script>

7.import必须是绝对地址或者相对地址。
Uncaught (in promise) TypeError: Failed to resolve module specifier “3.js”. Relative references must start with either “/”, “./”, or “../”.

参考文章:
万岁,浏览器原生支持ES6 export和import模块啦!

此条目发表在JavaScript, 浏览器, 规范分类目录。将固定链接加入收藏夹。

发表评论

邮箱地址不会被公开。 必填项已用*标注