打字稿:找不到名称空间

新手上路,请多包涵

我有以下简单的 NodeJS 代码:

 const express = require('express');

const server: express.Application = express();

我正在将 Typescript 添加到我的项目中并且是新手所以请原谅我。使用上面的代码我得到以下问题/错误:

对于要求:

 var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.

对于 express.Application 用法:

 Cannot find namespace 'express'.

如果我将“require”切换为“import”,它会修复命名空间错误,但不再是有效的节点代码,因此不会运行(抛出有关导入的意外令牌的新错误)。

使用 Typescript 编写这样的 Node 代码以避免这些错误的正确方法是什么?

我的 tsconfig.json 看起来像这样:

 {
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
  },
  "exclude": ["node_modules"],
}

原文由 CaribouCode 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 237
2 个回答

在浪费了很多时间之后,事实证明这是由于 tsconfig 文件中的 module 设置,它应该是:

 "module": "commonjs"

这意味着 Typescript 将输出通用的 js 模块而不是 ES6 模块,这意味着代码将像 NodeJS 代码一样正确运行。因此,我能够更改导入要求,因为它可以编译。

原文由 CaribouCode 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你是 React 开发人员,并且像我一样在这里结束 - 如果文件中有 JSX 语法,请尝试将文件的扩展名从 .ts 更改为 .tsx

原文由 a2f0 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题