从 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";