我有下面的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.我该如何解决这个问题?
发布于 2022-03-28 14:07:32
如果您使用特定的文件路径从命令行调用tsc,它将忽略您的tsconfig.json
打字本文档(https://www.typescriptlang.org/docs/handbook/tsconfig-json.html):
当在命令行上指定输入文件时,将忽略tsconfig.json文件。
这意味着,如果调用esModuleInterop,则tsconfig.json的tsc index.ts部分将没有任何效果。
可以通过使用import * as express from 'express';来解决这个问题,但是可能还有其他一些问题是由于忽略TS吐露而引起的。
tsc -w && node index.js的一个问题(来自其中一个注释)是,-w会让它等待而不是自行终止,这意味着您不会在"&&“之后到达该部分。
因此,您将不会进入node index.js部分。
(但至少这次,tsc没有得到一个特定的文件,因此配置不会被忽略)
另外,在您的配置中,outDir被设置为dist,所以编译的文件将放在那里。因此,您应该使用以下方法:
tsc && node ./dist/index.js
https://stackoverflow.com/questions/71643703
复制相似问题