ES6模块

ES6导出:

  1. // 单独导出
  2. export let a = 1
  3. // 批量导出
  4. let b = 1;
  5. let c = 2;
  6. export {b, c}
  7. // 导出接口
  8. export interface p {
  9. x: number;
  10. y: number;
  11. }
  12. // 导出函数
  13. export function f() {}
  14. // 导出时取别名
  15. function g() {}
  16. export {g as G}
  17. // 默认导出,无需函数名
  18. export default function() {
  19. console.log('i am default')
  20. }
  21. // 引入外部模块,重新导出
  22. // export {str as hello} from './b'
  23. /*
  24. b.ts
  25. export const str = 'hello'
  26. */

ES6导入:

  1. import { a, b, c } from './a'; // 批量导入
  2. console.log(a, b, c) // 1 1 2
  3. import { P } from './a'; // 导入接口
  4. // 导入接口,进行结束变量
  5. let p: P = {
  6. x: 1,
  7. y: 2
  8. }
  9. import { f as F } from './a'; // 导入时起别名
  10. import * as All from './a'; // 导入模块中所有成员,绑定在All上
  11. console.log(All)
  12. import myFunction from './a' //默认导入,不加{},导入默认
  13. myFunction()

CommonJS模块

CommonJS导出:

  1. // 整体导出
  2. let a = {
  3. x: 1,
  4. y: 2
  5. }
  6. module.exports = a
  7. // 导出多个变量
  8. // exports === module.exports
  9. exports.c = 3
  10. exports.d = 5

CommonJS导入:

  1. let c1 = require('./a.node')
  2. let c2 = require('./b.node')

因为node无法执行ts文件,所有安装ts-node

  1. npm i ts-node -g
  2. // 安装成功之后
  3. ts-node ./src/node/c.node.ts
  1. // 编译模板ts文件
  2. tsc ./src/es6/c.ts -t es3 (指定-t之后,编译就会忽略tsconfig.json中的target配置)
  3. tsc ./src/es6/c.ts -t es5 (编译成es5)
  4. tsc ./src/es6/c.ts -m amd (指定-m之后,编译就会忽略tsconfig.json中的module配置)

顶级导出
注意:两个模块系统尽量不要混用。