在ES6前, 常用的模組概念是 CommonJS , require 引入模組與 exports 匯出模組。 到了 ES6 則新增了 import 與 export 來進行引入匯出的方式。TypeScript 也沿用支援。今天來了解 ES Module Syntax 、 TypeScript 的 ES Module Syntax 、CommonJS Syntax。
若有錯誤,歡迎留言指教,感恩的心。
只匯出一個變數或function等,可使用 export default
:
// @filename: hello.ts
export default function helloWorld() {
console.log("Hello, world!");
}
import name
from
import hello from "./hello.js";
hello();
如果要匯出的變數或function等不只一個,可使用 export
:
// @filename: maths.ts
export var pi = 3.14;
export let squareTwo = 1.41;
export const phi = 1.61;
export class RandomNumberGenerator {}
export function absolute(num: number) {
if (num < 0) return num * -1;
return num;
}
import {name
} from
import { pi, phi, absolute } from "./maths.js";
console.log(pi);
const absPhi = absolute(phi);
const absPhi: number
name
fromname
} from除了上面普遍使用的2種 import 方法,還有一些有關import的用法:
使用關鍵字as
:
import { pi as π } from "./maths.js";
console.log(π);
// @filename: maths.ts
export const pi = 3.14;
export default class RandomNumberGenerator {}
使用 ,
去銜接:
// @filename: app.ts
import RNGen, { pi as π } from "./maths.js";
console.log(π);
* as name
take all into a single namespace匯入全部*
並命名 math
:
import * as math from "./maths.js";
console.log(math.pi);
const positivePhi = math.absolute(math.phi);
import "./file"
直接匯入檔案執行:
// @filename: app.ts
import "./maths.js";
console.log("3.14");
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
export interface Dog {
breeds: string[];
yearOfBirth: number;
}
// @filename: app.ts
import { Cat, Dog } from "./animal.js";
type Animals = Cat | Dog;
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
export type Dog = { breeds: string[]; yearOfBirth: number };
export const createCatName = () => "fluffy";
// @filename: valid.ts
import type { Cat, Dog } from "./animal.js";
export type Animals = Cat | Dog;
// @filename: app.ts
import type { createCatName } from "./animal.js";
const name = createCatName();
// @filename: app.ts
import { createCatName, type Cat, type Dog } from "./animal.js";
export type Animals = Cat | Dog;
const name = createCatName();
function absolute(num: number) {
if (num < 0) return num * -1;
return num;
}
module.exports = {
pi: 3.14,
squareTwo: 1.41,
phi: 1.61,
absolute,
};
const maths = require("maths");
maths.pi;
const { squareTwo } = require("maths");
squareTwo;
感謝閱讀,明天見!
https://www.typescriptlang.org/docs/handbook/2/modules.html