1 | What is a module?
Modules are particularly useful for a number of reasons. By separating code with similar logic into files called modules, we can:
- find, fix, and debug code more easily;
- reuse and recycle defined logic in different parts of our application;
- keep information private and protected from other modules;
- and, importantly, prevent pollution of the global namespace and potential naming collisions, by cautiously selecting variables and behavior we load into a program.
2 | Module systems
Node.js supports 2 ways of importing and exporting modules. There are 2 module systems, that are not fully compatible between each other:
- The CommonJS module system, with the use of the
moduleobject and the
- The ES6 module system, with the use of the standard ES6 keywords
Node.js can know what module system to use to export and import a file in 2 different ways.
2.1 | By checking the file extension
- Files that end with the extension .mjs are always exported and imported as ES6 modules, with the standard ES6 keywords
export. Node.js does not provide a
require()function for the .mjs files.
Files that end with the extension .cjs are always exported and imported as CommonJS modules.
In this case, Node.js provides a
require()function, and it will throw a
SyntaxErrorif you use
Because there is an enormous amount of existing Node.js code written using CommonJS module format, Node.js allows ES6 modules to load CommonJS modules using the
The reverse is not true, however: a CommonJS module cannot use
require() to load an ES6 module.
2.2 | By checking the package.json file
For files that do not have an explicit .mjs or .cjs extension, but just a generic .js extension, Node.js looks for a file named package.json in the same directory as the file and then in each of the containing directories (upper directories).
Once the nearest package.json file is found, Node.js checks for a top-level
type property in the JSON object. If the value of the
type property is
'module', then Node.js loads the file as an ES6 module.
If the value of that property is
'commonjs', then Node.js loads the file as a CommonJS module. Note that you do not need to have a package.json file to run Node.js programs: when no such file is found (or when the file is found but it does not have a
type property), Node.js defaults to using CommonJS modules.
This package.json trick only becomes necessary if you want to use ES6 modules with Node.js and do not want to use the .mjs file extension.
Author: Dimitri Alamkan
Initial publication date: