为什么 TypeScript 找不到安装到 'node_modules' 中的模块?

Why can't TypeScript find modules that are installed into 'node_modules'?

给定以下目录结构:

{project}/
  |-- node_modules/
  |    |-- lodash
  |-- src/
  |    |-- index.ts
  |-- lib/ (output)
  |    |-- index.js
  |    |-- index.d.ts
  |-- package.json
  |-- tsconfig.json

虽然构建的输出功能正常;当我使用以下任何一项时,tsc 命令抱怨它无法解析 lodash 模块:

import _ from "lodash";
import _ = require("lodash");
import * as _ from "lodash";

在我的 'tsconfig.json' 文件中,我包含了以下内容:

...

"target": "es6",
"sourceMap": true,
"module": "commonjs",
"moduleResolution": "node",

...

但尽管如此,它仍然找不到任何使用 npm 安装的模块。

我是否缺少让 TypeScript 找到这些模块所需的东西?

我意识到没有 TypeScript 定义文件,TypeScript 无法提供额外的类型检查;但是,这些肯定应该默认为 any 类型吧?

由于 lodash 在 node_modules/lodash 文件夹中没有定义文件,因此无法使用。您必须使用打字或使用环境声明而不是导入来下载它:

declare var _: any;

对于 node.js 你必须使用:

var _ = require('lodash');