tags : Javascript

The difference

ESM

  • is a web standard
  • ESM can consume and use CommonJS modules
  • node ecosystem as of 2023 has not properly moved to esm, so better to stick w commonjs w node
  • ESM is made better use of via bundlers for the web. So for web, esm is fine, for node, not so good.
  • import is an asynchronous (esm)

CommonJS

  • Not a web standard
  • CommonJS cannot consume ESM modules easily, it needs extra loader/transpiler or using dynamic imports
  • Using dynamic import means you need to deal w promises and put things in IIFE
  • require is synchronous (commonjs)

Modules

  • modules on the other hand can be only commonjs, or only esm or both. So we need to be aware of that aswell.
  • eg. jest does don’t work otb on esm or something like that

More brain fry w ts

  • When writing typescript, you can write something that looks like ESM with import/export, while targeting CJS