70 %
Chris Biscardi

nodejs ESModules and CommonJS interactions with import, require, and dynamic import

There are three core ways to "import" code in node v12+: require, import, and dynamic import().

CommonJS env

Inside a CommonJS environment, you can use require or import().

  • require always returns CommonJS.
  • import() can import ESM or CJS

ES Modules env

Inside an ES Modules environment, you can use import, import(), or createRequire.

  • import can return ESM or CJS, and even support named imports for CJS as of node v14.13
  • import() can import ESM or CJS
  • require is not available in ESM environments, but we can use createRequire to construct our own require. The require function returned from createRequire can only return CJS.