首页 > 解决方案 > TypeScript 导入使用正确的标志导入 Express 时出错

问题描述

我正在尝试使用 TypeScript 编写 Express 服务器。一切都是从头开始编写的,而不是 CLI,所以我确信我的设置中存在错误。

我想像import express, { Application } from express在我写过的其他服务器中一样写,但我得到了错误:

import express from 'express'
         ~~~~~~~

  node_modules/@types/express/index.d.ts:115:1
    115 export = e;
        ~~~~~~~~~~~
    This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

TS 配置:

{
    "compilerOptions": {
      "target": "es5",
      "module": "esnext",
      "moduleResolution": "node",
      "experimentalDecorators": true,
      "allowJs": true,
      "noEmit": true,
      "strict": true,
      "noImplicitAny": true,
      "esModuleInterop": true,
      "allowSyntheticDefaultImports": true,
      "forceConsistentCasingInFileNames": true
    },
    "exclude": [
        "node_modules"
    ]
  }

和包JSON:

"dependencies": {
    "@types/bcrypt": "^3.0.0",
    "@types/body-parser": "^1.19.0",
    "@types/knex": "^0.16.1",
    "@types/moment": "^2.13.0",
    "bcrypt": "^4.0.1",
    "body-parser": "^1.19.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "knex": "^0.20.13",
    "moment": "^2.24.0",
    "pg": "^8.0.0",
    "tsc": "^1.20150623.0",
    "typescript": "^3.8.3"
  },
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-typescript": "^7.9.0",
    "@types/express": "^4.17.4"
  }

Babel 目前未使用。我也尝试过改变module,但没有运气。

标签: typescriptexpress

解决方案


这个问题是"noEmit": true因为它阻止了任何输出,所以当然我在运行“tsc”后没有看到任何变化。

我在运行时特别看到了错误消息,tsc server.ts因为使用参数或标志运行将忽略tsconfig.json使用默认标志,因此运行tsc server.ts --esModuleInterop产生了预期的结果。

这就是为什么我从头开始运行它,所以我想我可以犯这样的愚蠢错误。希望遇到此问题的任何其他人都能更好地了解“tsc”和“tsconfig.json”如何相互作用。


推荐阅读