在nest.js中使用导入ESM模块会给出[ERR_REQUIRE_ESM]:不支持ES模块的require()

Tom*_*Tom 6 typescript nestjs

我将 Nest.js 与打字稿一起使用并想添加

import { DRACOLoader, GLTFLoader, TextureLoader } from 'node-three-gltf'; 
Run Code Online (Sandbox Code Playgroud)

在我的一个模块中。但这会导致以下错误

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)
Run Code Online (Sandbox Code Playgroud)

我使用的 node-三-gltf@1.0.3 只是一个 esm 模块。导致我在打字稿模块/控制器中使用 ESM 导入语法来导入 ESM 模块 node- Three-gltf 并收到此错误(至少对我来说 - 对这个问题相当陌生)奇怪的情况。

似乎是因为我的项目的 Nest.js 构建将我的 ES 语法转换为 CJS 语法,从而用 require 替换了我的导入,但没有转换 node-3-gltf 模块,然后抱怨。

我的 tsconfig 是这样的:

{
   "compilerOptions": {
      "module": "commonjs",
      "moduleResolution": "Node",
      "target": "esnext",
...
Run Code Online (Sandbox Code Playgroud)

理论上我看到以下选项:

  • 确保我将所有内容构建为 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-三-gltf提供cjs版本作为构建,看来我可以提出PR,但需要了解该依赖项的构建工具,所以不是一个很好的选择
  • 升级到node-三-gltf@1.10.0,因为它有一个cjs导出,但是需要Node 18,由于我无法控制的原因,我目前无法在生产中使用它
  • 调整 Nest.js 构建方式,将 esm 依赖项转换为 cjs - 我不知道该怎么做。

所以我想知道 sb 是否可以建议我如何调整 Nest.js 构建配置以对依赖项进行 esm->cjs 转换,或者为我指明另一个方向?

谢谢!时间

Mic*_*evi 1

我相信您应该在应用程序中继续使用 CJS,并使用表达式import()来加载仅 ESM 的包。

请参阅:将仅依赖于 ESM 库的包编译为 CommonJS 包