es6-export

Ts 模块导入导出

1
2
3
4
5
6
// AA.ts
const AA = {
key: 'value',
fun: () => console.log(123)
};
export = AA;
1
2
3
4
5
6
7
8
9
// Test.ts
// 1.------
import AA = require('./AA');
AA.fun();
AA.key;
// 2.------
import * as AAA from './AA';
AAA.fun();
AAA.key;

1
2
3
4
5
6
// AA.ts
const AA = {
key: 'value',
fun: () => console.log(123)
};
export default AA; // 等价于commonJS里 module.exports = AA;
1
2
3
4
5
6
7
8
9
// Test.ts
// 1.------
import AA from './AA';
AA.fun();
AA.key;
// 2.------
import * as AAA from './AA';
AAA.default.fun();
AAA.default.key;

ES6 模块加载 CommonJS 模块

CommonJS 模块的输出都定义在 module.exports 这个属性上面。Node 的 import 命令加载 CommonJS 模块,Node 会自动将 module.exports 属性,当作模块的默认输出,即等同于 export default

下面是一个 CommonJS 模块。

1
2
3
4
5
6
7
8
9
10
11
// a.js
module.exports = {
foo: 'hello',
bar: 'world'
};

// 等同于
export default {
foo: 'hello',
bar: 'world'
};

import 命令加载上面的模块,module.exports 会被视为默认输出,即 import 命令实际上输入的是这样一个对象{ default: module.exports }

所以,一共有三种写法,可以拿到 CommonJS 模块的 module.exports。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 写法一
import baz from './a';
// baz = {foo: 'hello', bar: 'world'};

// 写法二
import { default as baz } from './a';
// baz = {foo: 'hello', bar: 'world'};

// 写法三
import * as baz from './a';
// baz = {
// get default() {return module.exports;},
// get foo() {return this.default.foo}.bind(baz),
// get bar() {return this.default.bar}.bind(baz)
// }