Es6模块化
导出模块:export和导入模块:import
export只能导出一个接口,不能直接导出一个变量。
什么是接口?
1、导出变量
导出一个变量(文件名: index.js)
a) export var a = 1
b) var a = 1
export {a}
//导入
import {a} from 'index.js'
导出多个变量(index.js)
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
export { firstName, lastName, year };
//导入
import {firstName, lastName, year} from 'index.js'
//或整体加载
import * as all from 'index.js'
all.firstName //'Michael'
default默认导出,导入导出都不用加{}
var firstName = 'Michael';
export default firstName
//导入时
import firstName from 'index.js'
2、导出函数(index.js)
导出一个函数
export function a () {
return 1
}
或
function a () {
return 1
}
export {a}
//导入
import {a} from 'index.js'
a()
<br /> default默认导出(index.js)
export default function () {
return 2
}
//默认导出函数时,导入时可以取任意名字读取函数
import fun from 'index.js'
fun() //2
参考资料:
模块化历史:https://huangxuan.me/js-module-7day/#/38
模块化指北:https://www.yuque.com/yinzhi/blog/gdquyk#8404e3ba
闭包:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures