TypeScript:只能使用 'esModuleInterop' 标志默认导入



我有以下index.ts:

import { User } from "./datatypes"
import express from 'express';
console.log("hello world")

这是我的package.json:

{
"name": "simple_app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "tsc index.ts && node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.0",
"express": "^4.17.3"
},
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "^17.0.23",
"ts-node": "^10.7.0",
"typescript": "^4.6.3"
}
}

这是我的tsconfig.json:

{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"resolveJsonModule": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist"
},
"lib": ["es2015"]
}

当我写npm run start时,我得到:

Module '"/mnt/c/Users/raffa/Desktop/simple_app/node_modules/@types/express/index"' can only be default-imported using the 'esModuleInterop' flag
2 import express from 'express';
~~~~~~~
node_modules/@types/express/index.d.ts:133:1
133 export = e;
~~~~~~~~~~~
This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

我该如何解决这个问题?

如果使用特定的文件路径从命令行调用tsc,它将忽略您的tsconfig.json

打字文档(https://www.typescriptlang.org/docs/handbook/tsconfig-json.html):

在命令行上指定输入文件时,tsconfig.json文件将被忽略。

这意味着如果调用tsc index.ts,tsconfig.json的esModuleInterop部分将不起作用。

使用import * as express from 'express';可以解决此问题,但忽略TS配置可能会产生其他问题。

tsc -w && node index.js的一个问题(来自其中一条注释(是-w会让它等待,而不是自己终止,这意味着你不会到达"0"之后的部分&amp&">
因此,您将无法进入node index.js部分。
(但至少这次,tsc没有得到一个特定的文件,因此配置不会被忽略(

此外,在您的配置中,outDir设置为dist,因此编译后的文件将转到那里。因此,您应该使用以下内容:
tsc && node ./dist/index.js

最新更新