簡體   English   中英

在 Nest.js 中對 ESM 模塊使用導入會給出 [ERR_REQUIRE_ESM]:不支持 ES 模塊的 require()

[英]Using import for an ESM Module in nest.js gives [ERR_REQUIRE_ESM]: require() of ES Module not supported

我將nest.js與typescript一起使用並想添加

import { DRACOLoader, GLTFLoader, TextureLoader } from 'node-three-gltf'; 

在我的一個模塊中。 但是,這會導致以下錯誤

c:\m3\dist\src\gltftest\gltftest.controller.js:23
const node_three_gltf_1 = require("node-three-gltf");
                          ^
Error [ERR_REQUIRE_ESM]: require() of ES Module c:\m3\node_modules\node-three-gltf\build\index.js from c:\m3\dist\src\gltftest\gltftest.controller.js not supported.Instead change the require of index.js in c:\m3\dist\src\gltftest\gltftest.controller.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (c:\m3\dist\src\gltftest\gltftest.controller.js:23:27)
    at Object.<anonymous> (c:\m3\dist\src\gltftest\gltftest.module.js:12:30)

而我使用的 node-three-gltf@1.0.3 只是一個 esm 模塊。 導致我在我的 typescript 模塊/控制器中使用 ESM 導入語法來導入 ESM 模塊 node-three-gltf 並得到這個錯誤的奇怪情況(至少對我來說 - 對這個來說是相當新的)。

似乎是由於我的項目的 nest.js 構建將我的 ES 語法轉換為 CJS 語法,因此用 require 替換了我的導入,但沒有轉換 node-three-gltf 模塊然后抱怨。

我的 tsconfig 是這樣的:

{
   "compilerOptions": {
      "module": "commonjs",
      "moduleResolution": "Node",
      "target": "esnext",
...

從理論上講,我看到以下選項:

  • 確保我將所有內容構建為 ESM(我嘗試通過將 tsconfig 中的模塊設置為 ES2020 並將“type”:“module”添加到我的 package.json 中,然后導致不同依賴項的新導入錯誤(

不支持 node_modules\connect-typeorm\out' 解析從 C:\m3\dist\src\main.js 導入的 ES 模塊您的意思是導入 connect-typeorm/out/index.js 嗎?

  • 確保 node-three-gltf 提供了一個 cjs 版本作為構建,看起來我可以提出一個 PR 但需要了解該依賴項的構建工具,所以不是很好的選擇
  • 升級到 node-three-gltf@1.10.0,因為它有一個 cjs 導出,但是它需要 Node 18,由於我無法控制的原因,我目前無法在生產中使用它
  • 以將 esm 依賴項轉換為 cjs 的方式調整 nest.js 構建 - 我不知道該怎么做。

所以我想知道 sb 是否可以建議我如何調整 nest.js 構建配置以對依賴項進行 esm->cjs 轉換或將我指向另一個方向?

謝謝!

我相信您應該在您的應用程序中使用 CJS,並使用import()表達式來加載僅限 ESM 的 package。

請參閱: 將僅依賴於 ESM 的庫的 package 編譯為 CommonJS package

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM