Typescript 實戰 --- (9)ES6與CommonJS的模塊系統


1、ES6模塊系統

1-1、export 導出

(1)、單獨導出

// a.ts

export let a = 1;

 

(2)、批量導出

// a.ts

let b = 2;
let c = 3;

export { b, c };

 

(3)、導出接口

// a.ts

export interface Info {
  name: string;
  age: number;
}

 

(4)、導出函數

// a.ts

export function f() {
  console.log('function f');
}

 

(5)、導出時 起別名

// a.ts

function g() {
  console.log('function g');
}

export { g as G }

 

(6)、默認導出,無需函數名

// a.ts

export default function() {
  console.log('default function');
}

 

(7)、導出常量

// b.ts

export const str = 'hello';

 

(8)、引入外部模塊,重新導出

// a.ts

export { str as hello } from './b';

 

1-2、import 導入

(1)、批量導入

import { a, b, c } from './a';

console.log('a, b, c: ', a, b, c);   // a, b, c:  1 2 3

 

(2)、導入接口

import { Info } from './a';

let jim: Info = {
  name: 'Jim Green',
  age: 12
}

console.log('jim', jim);   // jim { name: 'Jim Green', age: 12 }

 

(3)、導入時 起別名

import { f as foo } from './a';

foo();   // function f

 

(4)、導入模塊中的所有成員,綁定在All上

import * as All from './a';

console.log(All.G());   // function g
console.log(All.g());   // 類型“typeof import("e:/study/ts-demo/es6/a")”上不存在屬性“g”

 

(5)、不加 {},導入默認

import myFunction from './a';

myFunction();   // default function

 

2、CommonJS 模塊系統

2-1、exports 導出

(1)、module.exports 整體導出

// a-node.ts

let a = {
  x: 2,
  y: 3
};

module.exports = a;

 

(2)、exports 導出多個變量

// b-node.ts

exports.c = 3;
exports.d = 4;

 

2-2、require 導入

let a1 = require('./a-node');
let b1 = require('./b-node');

console.log(a1);   // {x: 2, y: 3}
console.log(b1);   // {c: 3, d: 4}

 

3、export = 和 import = require()

當一個模塊使用 ES6模塊導出,CommonJS模塊導入時,就會出現模塊不兼容的情況

let a2 = require('../es6/a.ts');

a2();   // Uncaught TypeError: a2 is not a function

 

理論上,調用a2 方法其實就是調用 a.ts 中 export.default 默認導出的那個方法,但是此處報錯了。這里有兩個解決方法:

(1)、調用 default 方法(不推薦)

let a2 = require('../es6/a.ts');

a2.default();   // default function

 

(2)、export = 語法

export = 語法定義一個模塊的導出對象,它可以是類、接口、命名空間、函數或枚舉

若要導入一個 export = 的模塊時,必須使用 ts 提供的特定語法 import module = require('module')

// d.ts

// export 會被編譯成 CommonJS中的 module.exports,同時,意味着這個模塊中不能再有其它的導出

export = function () {
  console.log('hello world');
}
import a3 = require('../es6/d');

a3();   // hello world

 

很多庫使用了 CommonJS 的導出方式,如 module.exports=a,這樣會導致使用ES的方式導入時失敗,如 import a from 'X'。因為ES會默認訪問 a 的 default 屬性。TypeScript 為了兼容,引入了 esModuleInterop 選項,在編輯時自動添加default屬性。
 
當開啟 tsconfig.json 中的 esModuleInterop 選項時,可以使用 ES6模塊的導入語法
import a3 from '../es6/d';

a3();   // hello world

 

如果關閉該選項,使用 ES6模塊語法導入時則會報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM