我有以下简单的 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 许可协议
在浪费了很多时间之后,事实证明这是由于 tsconfig 文件中的
module
设置,它应该是:这意味着 Typescript 将输出通用的 js 模块而不是 ES6 模块,这意味着代码将像 NodeJS 代码一样正确运行。因此,我能够更改导入要求,因为它可以编译。