TomFree
TomFree

Reputation: 1389

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

I use nest.js with typescript and wanted to add

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

in one of my modules. However that results in below error

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)

And [email protected] which I use is just an esm module. Resulting in the (at least to me - fairly new to this suff) weird situation of me using ESM import syntax in my typescript module/controller to import the ESM module node-three-gltf and getting this error.

Seems to be due to the fact that nest.js build of my project transforms my ES syntax to CJS syntax and thus replaces my import with require but does not transform the node-three-gltf module and then complains.

my tsconfig goes like this:

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

Theoretically I see the following options:

node_modules\connect-typeorm\out' is not supported resolving ES modules imported from C:\m3\dist\src\main.js Did you mean to import connect-typeorm/out/index.js?

So I wonder if sb can advise me on how to adjust the nest.js build config to do the esm->cjs transformation for dependencies or point me in another direction?

Thanks! T

Upvotes: 10

Views: 26094

Answers (1)

Micael Levi
Micael Levi

Reputation: 6675

I believe you should stay with CJS in your app, and use the import() expression to load that ESM-only package.

See: Compile a package that depends on ESM only library into a CommonJS package

Upvotes: 2

Related Questions