前言
今天来讲解一下ES6的原生模块化,模块化就是把程序拆分成一个一个的文件,然后通过搭积木一样的方式把这些文件最后整合一个完整的程序。再ES6之前,js并没有自己的模块化体系,一般借助第三方工具,为了避免全局污染问题经常使用闭包,IIFE(立即调用函数表达式)等等再ES6之前是随处可见的。再ES6发布后引入了原生的模块化Module,使用模块化有如下好处。
1.代码高度可重复利用。
2.避免全局污染,每一个模块都有自己独立的空间。
3.更利于升级和维护
4.适合团队协作。
ES6原生模块化使用方法
1.编写模块文件
export default { id:1 }//保存为test.js 放置再根目录下
2.为<script> 加入type="module"属性,并引入文件。
<script type="module" src="./test.js"></script>
3.通过import导入模块
<script type="module"> import test from "./test.js" console.log(test) </script>
至此整个流程就演示完毕了,浏览器运行后就得到test.js的值。需要注意的事项如下
1.必须再script里加入type="module",否则你将收获一个浏览器的报错信息.
2.import里from的值必须为 / ./ ../ 这3种路劲格式,不能像这样import test from "test.js"。
3.module主要export import2个命令。export用来暴露一个接口,import用来接收暴露的接口.。
export
我们把我们需要的数据通过export给暴露出去。就是如果我这个文件想给与使用者什么东西,那我就通过export给出去,没给出去的别人也就拿不到。export也就相当于一个通道的作用。数据通过我export传输给使用者,下面是export一系列的用法示例。
export default "我是首模块" export Const a="我是字符模块" export const b= { info:"我是一个对象模块" } //花括号暴露接口 Let c={},d= {} export {c,d} //重命名接口使用关键字as let e=()=>{ alert(3) } export {e as NewName} //此代码存为test.js 在讲解到import的时候可用
可以看到,一个文件可以包含多个export,但是,请注意一个文件只允许有一个或则零个export default 。它的引入方法后面会讲。export的模块必须与暴露的对象建立对应的关系。
错误的export示例
//错误:不能直接给与值 export "示例" //错误:必须用{}除非使用export default let a="示例2" export a; //错误:export必须处于顶层 let c="示例3" let b=(function (){ export c; })()
import
在讲解export的时候我们做了一个test.js现在可以使用它了。import的作用就是接收export并把它们给保存起来。
<script type="module"> //export default暴露的对象可以取任何名字而且不能使用花括号{} import test from "./test.js" //export default import {a} from "./test.js" //export const a import {b} from "./test.js" //export const b import {c,d} from "./test.js" //export {c,d} import {NewName} from "./test.js" //export {e as NewName} import {f as nf } from "./test.js" //export {f} //export {f}在import时可通过关键字as改名 console.log(test,a,b,c,d,NewName(),nf) </script>
除了使用export default不使用花括号外,其他的export在import的时候必须使用花括号。