Soorya J
Soorya J

Reputation: 145

CommonJS require() or ES6 import/export in nodejs production?

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

Upvotes: 0

Views: 2301

Answers (1)

zirkelc
zirkelc

Reputation: 1723

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.

Upvotes: 1

Related Questions