我有以下內容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.
我怎么解決這個問題?
uj5u.com熱心網友回復:
如果您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://www.uj5u.com/ruanti/451104.html
上一篇:如何允許通過標頭訪問>用戶代理
