一.模块
模块:将一个大程序拆分成互相依赖的小文件(js文件),再用简单的方法拼装起来。
L : 从其他js文件中导入变量/函数
<script type="module" src="fs.js"></script>
// ES6加载模块 import { stat, exists, readFile } from 'fs';
二.import 和 export
export
规定模块的对外接口,import
输入其他模块提供的功能。
一个模块就是一个独立的文件。该文件内部的所有变量,外部无法获取。如果你希望外部能够读取模块内部的某个变量,就必须使用export
关键字输出该变量
1.export
// profile.js export var firstName = 'Michael';
或者:
// profile.js var firstName = 'Michael'; export {firstName};
//改变名字:export { firstName as fname };
2.import
加载模块:
import {firstName, lastName, year} from './profile';
//改名:import { lastName as surname } from './profile';
//整体加载
import * as circle from './circle';
console.log('圆面积:' + circle.area(4));
import
命令具有提升效果,会提升到整个模块的头部,首先执行。
3.export default
模块指定默认输出:
export default function () {
console.log('foo');
}
//其他模块加载该模块时,import命令可以为该匿名函数指定任意名字。
import customName from './export-default';
customName(); // 'foo'
三.ES6模块加载的实质
1.ES6模块加载的机制,与CommonJS模块完全不同。CommonJS模块输出的是一个值的拷贝,而ES6模块输出的是值的引用。
2.main.js
从lib.js
输入变量obj
,可以对obj
添加属性,但是重新赋值就会报错。因为变量obj
指向的地址是只读的,不能重新赋值,这就好比main.js
创造了一个名为obj
的const变量。
3.export
通过接口,输出的是同一个值。不同的脚本加载这个接口,得到的都是同样的实例。
---------------------------------------------------------------------------------------------------------------------------------------------------------
参考链接:ES6新特性6:模块Module