【问题标题】:Error importing node modules in TypeScript在 TypeScript 中导入节点模块时出错
【发布时间】:2015-11-02 20:21:33
【问题描述】:

今天早上我遇到了一个让我发疯的问题。我会解释这个问题,然后我会在下面提供我的答案(这样遇到这个问题的其他人可以更快地找到解决方案)。

只需发出以下命令,就很容易复制问题:

tsd query react --action install
mkdir src
echo "import React = require('react');" > src/foo.ts

我还在src 中包含了以下tsconfig.json 文件:

{
    "version": "1.6.2",
    "compilerOptions": {
        "outDir": "./tsdir",
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": true,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "files": [
        "foo.ts"
    ]
}

如果我尝试通过在 src 中简单地运行 tsc(版本 1.6.2)命令来编译它,我会得到:

foo.ts(1,24): error TS2307: Cannot find module 'react'.

我觉得莫名其妙的是,我已经使用 tsd 安装了 react 绑定,但是当我运行 tsc 时,我收到了这个错误。看起来我做的一切都是正确的,为什么会出现错误?

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    所以我最终想通的是,我需要在我的"files" 列表中明确包含typings 文件,即,

    {
        "version": "1.6.2",
        "compilerOptions": {
           ...
        },
        "files": [
            "foo.ts",
            "../typings/react/react.d.ts"
        ]
    }
    

    换句话说,我必须在"files" 中明确包含typings 文件。我真的不知道为什么。我认为tsc 足够聪明,可以自己寻找它们。

    如果有更好的解决方案不需要在"files" 中明确列出所有.d.ts 文件,我会全力以赴。但我只想指出,这至少是一种解决方法。

    【讨论】:

      猜你喜欢
      • 2012-11-03
      • 2013-08-25
      • 2017-04-03
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2015-08-12
      • 2019-02-27
      相关资源
      最近更新 更多