Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to import ESM inside nestjs?

I want to use this package called Ora from npm.

So, I did this:

$ npm i ora

Then, inside my project, I simply did:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import ora from 'ora'

But in my terminal, I got this error:

╰─>$ npm run start:dev                                                                                                                                               00:01:11

> api.stb-radiusmanager_nestjs@0.0.1 start:dev
> cross-env NODE_ENV=development nest start --watch


 Info  Webpack is building your sources...

webpack 5.92.1 compiled successfully in 433 ms
Type-checking in progress...
~/dist/main.js:517
module.exports = require("ora");
                 ^

Error [ERR_REQUIRE_ESM]: require() of ES Module ~/node_modules/ora/index.js from ~/dist/main.js not supported.
Instead change the require of index.js in ~/dist/main.js to a dynamic import() which is available in all CommonJS modules.
    at Object.ora (~/dist/main.js:517:18)
    at __webpack_require__ (~/dist/main.js:541:42)
    at ./libs/dma/src/providers/dma-client-provider/dma-client-provider.ts (~/dist/main.js:246:15)
    at __webpack_require__ (~/dist/main.js:541:42)
    at ./libs/dma/src/dma.module.ts (~/dist/main.js:25:31) {
  code: 'ERR_REQUIRE_ESM'
}

Node.js v21.4.0
No errors found.

How to solve this issue?


Stuff I have tried so far.

Change tsconfig.json to this:

"module": "NodeNext",
"moduleResolution": "NodeNext",

And changed the import statement to dynamic import:

async function myFunction(){
  const ora = (await import('ora')).default
}

But I got the same error.

>Solution :

you can search on how to import a ESM-only package in a CommonJS project. This is not a nestjs thing, it’s a Node.js error. So check this out Unable to import ESM module in Nestjs

One way would be:

const dynamicImport = async (packageName) =>
  new Function(`return import('${packageName}')`)()

// ...
const ora = await dynamicImport('ora').then(p => p.default)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading