Search code examples
node.jstypescriptnestjs

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:

import ora from 'ora'

But in my terminal, I got this error:

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

> [email protected] 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)