ES 6中具有对象、继承、封装等特性方便我们来对一个具体来实现,但是在使用的时候不能像java与C#中具有包或命名空间的模块意识,在使用的时候没有解决引用的方案,因此,ES 6是有一个模块化的方式来提供解决方案。
模块化主要由export、import两个命令来规定接口的相关信息和使用方式。
//module.js
export let temp="这是一个临时变量";
export let isTrue=false;
export function run(){
console.log("hellow");
}
//main.js
import { temp, isTrue, run } from "./module";
console.log(temp,isTrue);
run();
module.js中使用export 输出两个变量及一个函数,在main.js中可以使用import 加载这个模块,在这里值得注意的是,import 和 export一个是输出接口,另一个是引用接口,其中的名称必须一致,如果大家在使用import 和 export 在node中运行的时候,报找不到import 或者export异常,那是因为node暂时没有兼容这种写法,只有require的写法,node中如果需要使用import 和export写法,需要在当前环境中安装babel-preset-es2015和es 6草案的 babel-preset-stage-3扩展功能,另外,export可以写在脚本中的任何位置,但是不可以写在块级作用域中, import 同样也可以写在任何位置,但是具有变量作用域提升的能力。
export也可以使用解构的方式导出变量,如下:
let temp = "这是一个临时变量";
let isTrue = false;
function run(){
console.log("hellow");
}
export { temp, isTrue, run };
import { temp, isTrue, run } from './module'
另外值得一提的是import、export与required它们导出和引用变量是有区别的,import 与 export 是动态的导入,而required非动态的,简单的说,import与export是对变量的引用赋值, required则是对变量的值进行copy,看例子:
//ES 6 模块化
//module.js
export let isTrue = false;
setTimeout(function() {
isTrue=true;
},1000);
//main.js
import { isTrue } from "./module.js";
console.log(isTrue); //false
setTimeout(function() {
console.log(isTrue); //true
},1000);
//Require
//module.js
module.exports.isTrue = false;
setTimeout(function() {
module.exports.isTrue = true;
},1000);
//main.js
let { isTrue } = require("./module.js");
console.log(isTrue); //false
setTimeout(function() {
console.log(isTrue); //false
},1000);
export 还有另一种用法,它可以将两个以上的脚本内容导入到一个脚本中引用,比如说,我们有a.js、b.js、c.js三个文件,现在我们要在c.js中使用a.js和b.js中的内容,b.js里面也使用了a.js里面的内容,如果我们使用export将a.js 和b.js引用到c.js中,就有点代码冗余了,我们来看例子:
//a.js
export let temp_a = "这里是A.js文件";
//b.js
export { temp_a } from "./a";
export let temp_b = "这里是B.js文件";
//c.js
import { temp_a, temp_b } from "./b";
console.log(temp_a);
console.log(temp_b);
ES 6里面除了这些导入,还有一个default的指令,语法为:export default xxxx, 它与export区别在于export可以多次使用,而export default只能使用一次,另外export导出的接口,import 必须要使用{}来指定接口,export default因为是默认导出,只有一次,所以import 可以不使用{}来指定接口,而且import 是可以对export default导出的接口进行重命名的,看例子:
//module.js
let temp="临时变量";
let isTrue=false;
export default { temp, isTrue };
//main.js
import module from './module'
console.log(module.temp, module.isTrue);
export default 的实际处理方法其实是将变量给到default变量上,然后ES6允许给default命名任何名字,所以可以使用命名的名字去使用(.)访问所有属性或函数。
ES 6 模块化export 还可以允许你将 export 与export default 混合使用,两种方式的引用则是用(,)隔开来区分使用,看例子:
//module.js
let temp = "临时变量";
let isTrue = false;
export let me = "module.js";
export default { temp, isTrue};
//main.js
import mod, { me } from "./module";
console.log(mod.temp, mod.isTrue); //临时变量 false
console.log(me); //module.js
这里值得注意的是import 引用export 和 export default混合使用时,应该先匹配export default的内容,然后用(,)隔开,再匹配export 的变量或者函数,否则会语法报错。