【问题标题】:Typescript: Cannot find namespace打字稿:找不到命名空间
【发布时间】: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


【解决方案1】:

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

"module": "commonjs"

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

【讨论】:

  • 如果反应开发人员在这里结束,我的问题是我在文件中有 JSX,必须将扩展名从 ts 更改为 tsx。
  • @a2f0 为我工作。也许值得它自己的答案?
【解决方案2】:

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

【讨论】:

  • 一大堆“谢谢”
【解决方案3】:

也许你必须使用 import 而不是 require

import * as express from 'express';

【讨论】:

  • OP 已经在他的问题中写道,这将修复错误,但不再是有效的节点代码,因此会引发另一个错误。
  • 这会导致Cannot invoke an expression whose type lacks a call signature. Type 'typeof e' has no compatible call signatures 的 express() 以及当我尝试运行代码时出现 Typescript 错误,因为导入不是有效的 NodeJS 代码,它无论如何都不会工作。
猜你喜欢
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 2021-09-20
  • 2021-02-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
相关资源
最近更新 更多