![](/img/trans.png)
[英]How to resolve Node.js ES6 (ESM) Modules with the TypeScript Compiler (TSC). TSC doesn't emit the correct file-ext
[英]TypeScript with Node.js ESM disagreement
Node.js ESM 的工作方式似乎與 TypeScript 不同。
它導致程序通過類型檢查但在運行時崩潰。
package.json
{
"dependencies": {
"@types/lodash": "^4.0.0",
"lodash": "^4.0.0",
"typescript": "^4.0.0"
},
"type": "module"
}
tsconfig.json
{
"compilerOptions": {
"module": "es2015"
}
}
a.ts
import { partition } from "lodash";
partition([1, 2, 3, 4], n => n % 2);
跑
npm install
node_modules/.bin/tsc -p .
node index.js
程序崩潰:
file:///home/paul/test44/index.js:1
import { partition } from "lodash";
^^^^^^^^^
SyntaxError: Named export 'partition' not found. The requested module 'lodash' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'lodash';
const { partition } = pkg;
at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:179:5)
at async Loader.import (node:internal/modules/esm/loader:178:24)
at async Object.loadESM (node:internal/process/esm_loader:68:5)
at async handleMainPromise (node:internal/modules/run_main:63:12)
如何將 TypeScript 和 Node.js ESM 帶入 alignment,以便類型檢查與運行時行為相匹配?
編輯:
我嘗試將 typescript@next 與"module": "nodenext"
使用。
發生同樣的錯誤。
問題是你混合了 ES 和 ComonJS 模塊; 它在錯誤消息的文本中。 這仍然是一個相對較新的概念,當您期望模塊......應該......正常工作時很容易錯過。
TypeScript 僅提供import
語句,然后它們將轉譯到您選擇的模塊系統; 在 ESM 的情況下,由於它們在語法上相似,所以沒有太多需要轉換的地方。
由於您要轉譯為 ESM,因此問題不在於 TypeScript; 它是底層 Node.js 引擎以及它如何處理混合模塊系統。 您已經在 ESM 中編寫了一些內容(授予,使用 TypeScript)並且您正在嘗試導入用 CommonJS 編寫的其他內容。
為了根據 CommonJS 模塊執行代碼,您需要:
module.createRequire()
以可用的形式導入 CommonJS 模塊資料來源:
https://nodejs.org/api/esm.html#no-require-exports-or-moduleexports https://nodejs.org/api/module.html#modulecreaterequirefilename
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.