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.tsexport const str = 'hello'*/
ES6导入:
import { a, b, c } from './a'; // 批量导入console.log(a, b, c) // 1 1 2import { 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.exportsexports.c = 3exports.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配置)
顶级导出
注意:两个模块系统尽量不要混用。
