Modules


1 | What is a module?


In JavaScript, a module represents a reusable piece of code and it is simply a file. It is possible to use code from another module (file) in a particular module (file) by importing and exporting modules.


Modules are particularly useful for a number of reasons. By separating code with similar logic into files called modules, we can:



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:



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



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 import keyword. 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:
Last updated: