Coo*_*oop 13 javascript node.js typescript
我有以下简单的 NodeJS 代码:
const express = require('express');
const server: express.Application = express();
Run Code Online (Sandbox Code Playgroud)
我正在将 Typescript 添加到我的项目中并且是新手,所以请原谅我。使用上面的代码,我得到以下问题/错误:
对于要求:
var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.
Run Code Online (Sandbox Code Playgroud)
对于 express.Application 用法:
Cannot find namespace 'express'.
Run Code Online (Sandbox Code Playgroud)
如果我将“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"],
}
Run Code Online (Sandbox Code Playgroud)
在浪费了很多时间之后,事实证明这是由于moduletsconfig 文件中的设置应该是:
"module": "commonjs"
Run Code Online (Sandbox Code Playgroud)
这意味着 Typescript 将输出常见的 js 模块而不是 ES6 模块,这意味着代码将作为 NodeJS 代码正确运行。因此,我能够将 require 更改为导入,因为它可以编译。
| 归档时间: |
|
| 查看次数: |
15170 次 |
| 最近记录: |