從 npm 匯入模組

如果你有模組的型別定義檔案(d.ts),則可以使用 import 語句。

import _ = require('lodash');

如果你沒有該模組的定義檔案,TypeScript 將在編譯時丟擲錯誤,因為它找不到你嘗試匯入的模組。

在這種情況下,你可以使用正常的執行時 require 函式匯入模組。然而,這將它返回為 any 型別。

// The _ variable is of type any, so TypeScript will not perform any type checking.
const _: any = require('lodash');

從 TypeScript 2.0 開始,你還可以使用簡寫環境模組宣告,以便在你沒有模組的型別定義檔案時告訴 TypeScript 模組是否存在。但是,在這種情況下,TypeScript 將無法提供任何有意義的型別檢查。

declare module "lodash";

// you can now import from lodash in any way you wish:
import { flatten } from "lodash";
import * as _ from "lodash";

從 TypeScript 2.1 開始,規則已經進一步放寬。現在,只要 node_modules 目錄中存在一個模組,TypeScript 就允許你匯入它,即使在任何地方都沒有模組宣告。 (注意,如果使用 --noImplicitAny 編譯器選項,下面仍會生成警告。)

// Will work if `node_modules/someModule/index.js` exists, or if `node_modules/someModule/package.json` has a valid "main" entry point
import { foo } from "someModule";