![](/img/trans.png)
[英]running node with loader ts-node/esm.js requires imports to have the .js extension
[英]Force TypeScript to generate export/imports with the ".js" extension; running Node 16?
擁有一個使用 ESM 模塊的 TS 4.7 庫。
tsconfig.json:
"target": "ES2020",
"module": "ES2020",
"lib": ["ES2020"],
"moduleResolution": "node",
package.json
"type": "module",
我有一個只有一個愚蠢的導出的主文件:
索引.ts
export { Spig } from './spig';
編譯為:
index.js
export { Spig } from './spig';
//# sourceMappingURL=index.js.map
當我從 Node CLI 程序(也啟用了 ESM 模塊)中使用這個庫時,我收到以下錯誤:
Cannot find module <path>/lib/spig imported from <path>/lib/index.js
當我在生成的index.js
中手動添加.js
時,問題就消失了:
export { Spig } from './spig.js';
如何強制 TypeScript 編譯器也生成擴展? 我在這里想念什么?
在 ESM 模塊導入中,您不能再省略文件擴展名。 對於 typescript 文件,擴展名應始終為.js
/ .jsx
,而不是.ts
/ .tsx
。 因此,在index.ts
中,如果使用 ESM 模塊,您應該將擴展名添加到spig
導出,以及導入/導出的所有其他文件。
索引.ts
export { Spig } from './spig.js';
此外, moduleResolution
應設置為Node16
或NodeNext
,以便 ESM 模塊按預期工作。
如文檔中所述(我強調):
相對導入路徑需要完整擴展(例如,我們必須編寫import "./foo.js"
而不是import "./foo"
)。
當.ts
文件被編譯為 ES 模塊時,ECMAScript 導入/導出語法在.js
output 中被單獨保留; 當它被編譯為 CommonJS 模塊時,它將產生與您今天在模塊:commonjs 下獲得的相同的 output。
這也意味着 ES 模塊和 CJS 模塊的.ts
文件之間的路徑解析不同。 例如,假設您今天有以下代碼:
// ./foo.ts
export function helper() {
// ...
}
// ./bar.ts
import { helper } from "./foo"; // only works in CJS
helper();
此代碼在 CommonJS 模塊中有效,但在 ES 模塊中會失敗,因為相對導入路徑需要使用擴展。 因此,它必須被重寫以使用 foo.ts 的foo.ts
的擴展 - 所以bar.ts
將不得不從./foo.js
導入。
// ./bar.ts
import { helper } from "./foo.js"; // works in ESM & CJS
helper();
起初這可能感覺有點麻煩,但 TypeScript 工具(如自動導入和路徑完成)通常會為您完成此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.