【发布时间】:2019-10-13 22:02:36
【问题描述】:
我有以下简单的 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”,它会修复命名空间错误,但不再是有效的 Node 代码,因此不会运行(引发有关导入的意外令牌的新错误)。
使用 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"],
}
【问题讨论】:
-
您的项目是如何设置的;
tsconfig.json中有什么内容? -
在顶部尝试
declare function require(name:string);。 Typescript 默认不支持 require -
@jonrsharpe 我已经用 tsconfig 更新了我的问题
-
@Deckerz 我是否必须在我使用 require 的每个 Node 文件中都这样做?如果是这样,那似乎很烦人。
-
npm i @types/express... 用于打字稿定义。它应该修复“找不到命名空间'express'。”
标签: javascript node.js typescript