[英]TypeScript & NodeJS: Exports is not defined in ES module scope
我用導入/導出語法編寫了我的 NodeJS JavaScript 文件,我的 package.json 有"type": "module"
問題是tsc
構建代碼后,/build/ /build/server.js
中的轉譯代碼無法運行。 它說Exports is not defined in ES module scope
這是我的tsconfig.json
{
"compilerOptions": {
"resolveJsonModule": true,
"incremental": true,
"target": "es2019" ,
"module": : "commonjs",
"allowJs": true ,
"outDir": "./build",
"strict": true ,
"noImplicitAny": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true ,
"alwaysStrict": true ,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true ,
"inlineSourceMap": true ,
"experimentalDecorators": true,
"emitDecoratorMetadata": true ,
"forceConsistentCasingInFileNames": true,
"useUnknownInCatchVariables": false
}
}
如果我刪除"module": "commonjs"
並添加"moduleResolution": "Node"
,我的導入會出現不同的錯誤:
找不到從 /build/server.js 導入的模塊 /build/constants模塊 /build/constants.js 確實存在,但在我的代碼中我沒有將 .js 添加到我的導入中,所以我像這樣import {CONSTANTS} from 'constants'
它import {CONSTANTS} from 'constants'
。
在 TypeScript 文件中,當導入其他 TypeScript 文件時,導入應該像import {CONSTANTS} from constants.js
或import {CONSTANTS} from constants.ts
或import {CONSTANTS} from constants
,這就是我現在擁有的。
我是 TypeScript 的新用戶。解決我遇到的這個問題的最佳方法是什么?
謝謝
將 tsconfig“module”和“target”更新為“ES6”解決了這個問題。
我找到了解決方案。 "type": "module"
必須從 package.json 中刪除
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.