TypeScript——模塊(3)

創(chuàng)建模塊結構指導

盡可能地在頂層導出

用戶應該更容易地使用你模塊導出的內容。 嵌套層次過多會變得難以處理,因此仔細考慮一下如何組織你的代碼。

從你的模塊中導出一個命名空間就是一個增加嵌套的例子。 雖然命名空間有時候有它們的用處,在使用模塊的時候它們額外地增加了一層。 這對用戶來說是很不便的并且通常是多余的。

導出類的靜態(tài)方法也有同樣的問題 - 這個類本身就增加了一層嵌套。 除非它能方便表述或便于清晰使用,否則請考慮直接導出一個輔助方法。

如果僅導出單個 class 或 function,使用 export default

就像“在頂層上導出”幫助減少用戶使用的難度,一個默認的導出也能起到這個效果。 如果一個模塊就是為了導出特定的內容,那么你應該考慮使用一個默認導出。 這會令模塊的導入和使用變得些許簡單。 比如:

MyClass.ts

export default class SomeType {

? constructor() { ... }

}

MyFunc.ts

export default function getThing() { return 'thing'; }

Consumer.ts

import t from "./MyClass";

import f from "./MyFunc";

let x = new t();

console.log(f());

對用戶來說這是最理想的。他們可以隨意命名導入模塊的類型(本例為t)并且不需要多余的(.)來找到相關對象。

如果要導出多個對象,把它們放在頂層里導出

MyThings.ts

export class SomeType { /* ... */ }

export function someFunc() { /* ... */ }

相反地,當導入的時候:

明確地列出導入的名字

Consumer.ts

import { SomeType, someFunc } from "./MyThings";

let x = new SomeType();

let y = someFunc();

使用命名空間導入模式當你要導出大量內容的時候

MyLargeModule.ts

export class Dog { ... }

export class Cat { ... }

export class Tree { ... }

export class Flower { ... }

Consumer.ts

import * as myLargeModule from "./MyLargeModule.ts";

let x = new myLargeModule.Dog();

使用重新導出進行擴展

你可能經常需要去擴展一個模塊的功能。 JS里常用的一個模式是JQuery那樣去擴展原對象。 如我們之前提到的,模塊不會像全局命名空間對象那樣去 合并。 推薦的方案是 不要去改變原來的對象,而是導出一個新的實體來提供新的功能。

假設Calculator.ts模塊里定義了一個簡單的計算器實現。 這個模塊同樣提供了一個輔助函數來測試計算器的功能,通過傳入一系列輸入的字符串并在最后給出結果。

Calculator.ts

export class Calculator {

? ? private current = 0;

? ? private memory = 0;

? ? private operator: string;

? ? protected processDigit(digit: string, currentValue: number) {

? ? ? ? if (digit >= "0" && digit <= "9") {

? ? ? ? ? ? return currentValue * 10 + (digit.charCodeAt(0) - "0".charCodeAt(0));

? ? ? ? }

? ? }

? ? protected processOperator(operator: string) {

? ? ? ? if (["+", "-", "*", "/"].indexOf(operator) >= 0) {

? ? ? ? ? ? return operator;

? ? ? ? }

? ? }

? ? protected evaluateOperator(operator: string, left: number, right: number): number {

? ? ? ? switch (this.operator) {

? ? ? ? ? ? case "+": return left + right;

? ? ? ? ? ? case "-": return left - right;

? ? ? ? ? ? case "*": return left * right;

? ? ? ? ? ? case "/": return left / right;

? ? ? ? }

? ? }

? ? private evaluate() {

? ? ? ? if (this.operator) {

? ? ? ? ? ? this.memory = this.evaluateOperator(this.operator, this.memory, this.current);

? ? ? ? }

? ? ? ? else {

? ? ? ? ? ? this.memory = this.current;

? ? ? ? }

? ? ? ? this.current = 0;

? ? }

? ? public handleChar(char: string) {

? ? ? ? if (char === "=") {

? ? ? ? ? ? this.evaluate();

? ? ? ? ? ? return;

? ? ? ? }

? ? ? ? else {

? ? ? ? ? ? let value = this.processDigit(char, this.current);

? ? ? ? ? ? if (value !== undefined) {

? ? ? ? ? ? ? ? this.current = value;

? ? ? ? ? ? ? ? return;

? ? ? ? ? ? }

? ? ? ? ? ? else {

? ? ? ? ? ? ? ? let value = this.processOperator(char);

? ? ? ? ? ? ? ? if (value !== undefined) {

? ? ? ? ? ? ? ? ? ? this.evaluate();

? ? ? ? ? ? ? ? ? ? this.operator = value;

? ? ? ? ? ? ? ? ? ? return;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? throw new Error(`Unsupported input: '${char}'`);

? ? }

? ? public getResult() {

? ? ? ? return this.memory;

? ? }

}

export function test(c: Calculator, input: string) {

? ? for (let i = 0; i < input.length; i++) {

? ? ? ? c.handleChar(input[i]);

? ? }

? ? console.log(`result of '${input}' is '${c.getResult()}'`);

}

下面使用導出的test函數來測試計算器。

TestCalculator.ts

import { Calculator, test } from "./Calculator";

let c = new Calculator();

test(c, "1+2*33/11="); // prints 9

現在擴展它,添加支持輸入其它進制(十進制以外),讓我們來創(chuàng)建ProgrammerCalculator.ts。

ProgrammerCalculator.ts

import { Calculator } from "./Calculator";

class ProgrammerCalculator extends Calculator {

? ? static digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];

? ? constructor(public base: number) {

? ? ? ? super();

? ? ? ? const maxBase = ProgrammerCalculator.digits.length;

? ? ? ? if (base <= 0 || base > maxBase) {

? ? ? ? ? ? throw new Error(`base has to be within 0 to ${maxBase} inclusive.`);

? ? ? ? }

? ? }

? ? protected processDigit(digit: string, currentValue: number) {

? ? ? ? if (ProgrammerCalculator.digits.indexOf(digit) >= 0) {

? ? ? ? ? ? return currentValue * this.base + ProgrammerCalculator.digits.indexOf(digit);

? ? ? ? }

? ? }

}

// Export the new extended calculator as Calculator

export { ProgrammerCalculator as Calculator };

// Also, export the helper function

export { test } from "./Calculator";

新的ProgrammerCalculator模塊導出的API與原先的Calculator模塊很相似,但卻沒有改變原模塊里的對象。 下面是測試ProgrammerCalculator類的代碼:

TestProgrammerCalculator.ts

import { Calculator, test } from "./ProgrammerCalculator";

let c = new Calculator(2);

test(c, "001+010="); // prints 3

模塊里不要使用命名空間

當初次進入基于模塊的開發(fā)模式時,可能總會控制不住要將導出包裹在一個命名空間里。 模塊具有其自己的作用域,并且只有導出的聲明才會在模塊外部可見。 記住這點,命名空間在使用模塊時幾乎沒什么價值。

在組織方面,命名空間對于在全局作用域內對邏輯上相關的對象和類型進行分組是很便利的。 例如,在C#里,你會從 System.Collections里找到所有集合的類型。 通過將類型有層次地組織在命名空間里,可以方便用戶找到與使用那些類型。 然而,模塊本身已經存在于文件系統之中,這是必須的。 我們必須通過路徑和文件名找到它們,這已經提供了一種邏輯上的組織形式。 我們可以創(chuàng)建 /collections/generic/文件夾,把相應模塊放在這里面。

命名空間對解決全局作用域里命名沖突來說是很重要的。 比如,你可以有一個 My.Application.Customer.AddForm和My.Application.Order.AddForm -- 兩個類型的名字相同,但命名空間不同。 然而,這對于模塊來說卻不是一個問題。 在一個模塊里,沒有理由兩個對象擁有同一個名字。 從模塊的使用角度來說,使用者會挑出他們用來引用模塊的名字,所以也沒有理由發(fā)生重名的情況。

危險信號

以下均為模塊結構上的危險信號。重新檢查以確保你沒有在對模塊使用命名空間:

文件的頂層聲明是export namespace Foo { ... } (刪除Foo并把所有內容向上層移動一層)

文件只有一個export class或export function (考慮使用export default)

多個文件的頂層具有同樣的export namespace Foo { (不要以為這些會合并到一個Foo中?。?/p>

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容