0
votes

I have got the latest version of npm modules and developing a nodejs application. The problem is that some npm modules support the require() and the others support the import/export statements, I cannot use them both in a file. Having the production criteria in mind, which should I opt for either only require() or only import/export or a mix of those using the dynamic import() along with the require(). Thanks

1
That depends on your Node.js version and if your package is defined as ESM or CommonJS package. See nodejs.org/api/packages.html#type Are you using JavaScript or TypeScript? - zirkelc
Hi @zirkelc, I m using javascript. How to find whether a npm module is deined as ESM or CommonJS ? Thanks for your reply - Soorya J
The package.json defines a type field with either module for ESM or commonjs for CommonJS. - zirkelc

1 Answers

1
votes

I assume we are talking about plain JavaScript without transpiling from TypeScript or Babel.

The require() function is used to load CommonJS modules whereas the import statement is used to load ESM modules. Which of them you should or can use depends on factors such as:

  • does your target Node.js version support ESM? I think ESM in Nodejs support got introduced in v12, but I'm not sure how stable it is.
  • is your package defined as ESM or CommonJS module. That depends on the type field in your package.json, with "type": "module" for ESM and "type": "commonjs" for CommonJS: https://nodejs.org/api/packages.html#type
  • are your package dependencies provided as ESM or CommonJS modules. That depends on each individual package.json and their type field as well as if the package is provided as both ESM and CommonJS modules with conditional exports: https://nodejs.org/api/packages.html#conditional-exports

Unfortunately, I cannot provide a definite answer for you because that depends on your environment. ESM and import statements are going to be the future of JS, but the ESM support in the Node.js ecosystem is not on par with CommonJS yet.

With this in mind, I would opt for CommonJS modules but I would use a transpiler like TypeScript so I can still use modern features of JS.