import和export

import和export

importexport 都要使用 {} 来包裹变量。

import

1
2
3
4
5
6
7
// 逐个引入
import {year, month, day} from "../components/date";
import {year as y, month as m, day as d} from "../components/date";

// 整体引入赋值给date
import * as date from "../components/date";
// 引用:date.year, date.month, date.day

import()

使用 import() 函数可以实现动态加载(按需加载),返回一个 promise 对象。

import()
1
2
3
4
5
6
7
8
9
10
11
import(url)
.then(function () {

// ...

})
.catch(function () {

// ...

});

export

1
2
3
4
5
6
7
// 写法一
export var year = 2012;
export function fn() {}

// 写法二
export { year, month, day };
export { year as y, month as m, day as d };

export default

import 一个模块时需要知道模块 export 的变量名。
如果不想看 export 的变量名而直接使用的话,可以使用 export default

export
1
export default ...;

这种写法不需要给date{}

import
1
import date from "../components/date";

评论