Enabling
History
Node.js has two module systems: CommonJS modules and ECMAScript modules.
By default, Node.js will treat the following as CommonJS modules:
-
Files with a
.cjsextension. -
Files with a
.jsextension or without an extension, when the nearest parentpackage.jsonfile contains a top-level field"type"with a value of"commonjs". -
Files with a
.jsextension or without an extension, when the nearest parentpackage.jsonfile doesn't contain a top-level field"type"or there is nopackage.jsonin any parent folder; unless the file contains syntax that errors unless it is evaluated as an ES module. Package authors should include the"type"field, even in packages where all sources are CommonJS. Being explicit about thetypeof the package will make things easier for build tools and loaders to determine how the files in the package should be interpreted. -
Files with an extension that is not
.mjs,.cjs,.json,.node, or.js, when the nearest parentpackage.jsonfile contains a top-level field"type"with a value of"module".
See Determining module system for more details.
Calling require() always use the CommonJS module loader. Calling import()
always use the ECMAScript module loader.