Package

CommonJS

Pure ESM package

CommonJS has served us well for many years, but ESM comes with many benefits, like language-level syntax, browser support, defaults to strict mode, async loading, top-level await, improved static analysis & tree-shaking, and more.

If you’re not familiar with ESM, start by reading the MDN overview. The Node.js docs on ESM are also very comprehensive, and IMHO required reading.

Introducing a new module system is not a simple thing. The ecosystem is huge and it’s going to take many years to move the whole ecosystem. Luckily, smart people have spent a lot of effort into making these module systems fairly compatible. ESM can import CommonJS and CommonJS can import ESM. However, and it’s a big however, CommonJS can only import ESM asynchronously.

Migrating

There are two ways to move your packages to ESM:

  • Pure ESM This has the benefit that it’s easier to set up. You just add "type": "module" to your package.json, require Node.js 12, update docs & code examples, and do a major release.
  • Dual — ESM with a build step that transpiles a CommonJS fallback This requires you to also set up a build step and add a exports field to your package.json. Read more

Backlinks