ES6模块
ES6导出:
// 单独导出
export let a = 1
// 批量导出
let b = 1;
let c = 2;
export {b, c}
// 导出接口
export interface p {
x: number;
y: number;
}
// 导出函数
export function f() {}
// 导出时取别名
function g() {}
export {g as G}
// 默认导出,无需函数名
export default function() {
console.log('i am default')
}
// 引入外部模块,重新导出
// export {str as hello} from './b'
/*
b.ts
export const str = 'hello'
*/
ES6导入:
import { a, b, c } from './a'; // 批量导入
console.log(a, b, c) // 1 1 2
import { P } from './a'; // 导入接口
// 导入接口,进行结束变量
let p: P = {
x: 1,
y: 2
}
import { f as F } from './a'; // 导入时起别名
import * as All from './a'; // 导入模块中所有成员,绑定在All上
console.log(All)
import myFunction from './a' //默认导入,不加{},导入默认
myFunction()
CommonJS模块
CommonJS导出:
// 整体导出
let a = {
x: 1,
y: 2
}
module.exports = a
// 导出多个变量
// exports === module.exports
exports.c = 3
exports.d = 5
CommonJS导入:
let c1 = require('./a.node')
let c2 = require('./b.node')
因为node无法执行ts文件,所有安装ts-node
npm i ts-node -g
// 安装成功之后
ts-node ./src/node/c.node.ts
// 编译模板ts文件
tsc ./src/es6/c.ts -t es3 (指定-t之后,编译就会忽略tsconfig.json中的target配置)
tsc ./src/es6/c.ts -t es5 (编译成es5)
tsc ./src/es6/c.ts -m amd (指定-m之后,编译就会忽略tsconfig.json中的module配置)
顶级导出
注意:两个模块系统尽量不要混用。