打字稿:找不到命名空间

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)

dps*_*dps 76

如果您是一个像我一样最终来到这里的 React 开发人员 - 如果文件中有 JSX 语法,请尝试将文件的扩展名从 更改.ts.tsx.

  • 我准备拔掉我的头发 (3认同)

Coo*_*oop 9

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

"module": "commonjs"
Run Code Online (Sandbox Code Playgroud)

这意味着 Typescript 将输出常见的 js 模块而不是 ES6 模块,这意味着代码将作为 NodeJS 代码正确运行。因此,我能够将 require 更改为导入,因为它可以编译。

  • 万一 React 开发人员在这里结束,我的问题是我的文件中有 JSX,并且必须将扩展名从 ts 更改为 tsx。 (5认同)