Using Import and Require in the same NodeJS project
Asked Answered
H

1

9

I have a Node.js project whose modules are imported in the Common.JS way using require. However, the need arose to import a package that is ESM only.

One way to use ESM import from in my project was to add "type": "module" to my package.json file. However, all the requires stoped working.

I verified that one solution would be to create the require module from the module package:

import { createRequire } from "module";
const require = createRequire(import.meta.url);

However, the entire (large) project has imports with require and it seems to me unfeasible to have to add this solution to each one of them.

So I'd like to know if there's an elegant way to declare require just once and have it be used throughout the project.

Or, is there any more elegant solution than creating the require or substituting everything for ESM?

Hulbert answered 19/7, 2022 at 22:59 Comment(0)
G
0

To use require and import together, you need to use dynamic import() expressions to load an ES module into a CommonJS context.

A common Node.js error message that provides a solution looks like this:

Error [ERR_REQUIRE_ESM]: require() of ES Module <path> from <path> not supported.
Instead change the require of <path> in <path> to a dynamic import() which is available in all CommonJS modules.

Here is an example of using lodash and lodash-es:

const lodash = require('lodash')

async function main() {
  const output = lodash.concat(['hello'], ['world'])
  const lodashEs = await import('lodash-es')

  console.log(lodashEs.join(output, ' '))
}

main()
Genu answered 25/2 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.