There are three core ways to "import" code in node v12+: require
, import
, and dynamic import()
.
Inside a CommonJS environment, you can use require
or import()
.
require
always returns CommonJS.import()
can import ESM or CJSInside 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.13import()
can import ESM or CJSrequire
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.