Published on

Day27 :【TypeScript 學起來】Module 模組

Authors

Day27 :【TypeScript 學起來】Module 模組

在ES6前, 常用的模組概念是 CommonJS , require 引入模組與 exports 匯出模組。 到了 ES6 則新增了 import 與 export 來進行引入匯出的方式。TypeScript 也沿用支援。今天來了解 ES Module Syntax 、 TypeScript 的 ES Module Syntax 、CommonJS Syntax。

若有錯誤,歡迎留言指教,感恩的心。


ES Module Syntax

export default

只匯出一個變數或function等,可使用 export default :

// @filename: hello.ts
export default function helloWorld() {
  console.log("Hello, world!");
}
import hello from "./hello.js";
hello();

export

如果要匯出的變數或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 { pi, phi, absolute } from "./maths.js";

console.log(pi);
const absPhi = absolute(phi);

const absPhi: number

Additional Import Syntax

import `name` from

import {`name`} form

除了上面普遍使用的2種 import 方法,還有一些有關import的用法:

import can be renamed

使用關鍵字as:

import { pi as π } from "./maths.js";

console.log(π);

mix and match into single import

// @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");

TypeScript 特有的 ES Module Syntax

type 及 interface

// @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;

import type

// @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();

Inline type imports

// @filename: app.ts
import { createCatName, type Cat, type Dog } from "./animal.js";

export type Animals = Cat | Dog;
const name = createCatName();

CommonJS Syntax

module.exports

function absolute(num: number) {
  if (num < 0) return num * -1;
  return num;
}

module.exports = {
  pi: 3.14,
  squareTwo: 1.41,
  phi: 1.61,
  absolute,
};

require

const maths = require("maths");
maths.pi;

結構

const { squareTwo } = require("maths");
squareTwo;

感謝閱讀,明天見!


參考資料

https://www.typescriptlang.org/docs/handbook/2/modules.html