Member-only story
Understanding module.exports and exports in Node.js.
Understanding module.exports and exports in Node.js.
In
Node.js
programming,modules
are self-contained units of functionality that are shareable and reusable. They make our lives as developers easier because we can use them to enhance our applications without having to write functionality ourselves. They also allow us to organize and decouple our code, making applications easier to understand, debug, and maintain.
Different Node.js
Module Formats
Due to the fact that JavaScript initially did not have the concept of modules, various competing formats have emerged over time. The following are the main formats:
- The Asynchronous Module Definition (
AMD
) format is used in browsers and defines modules using define functions. CommonJS
(CJS
) format is used inNode.js
and usesrequire
andmodule.exports
to define dependencies and modules. Thenpm
ecosystem is built on top of this format.ES
module (ESM
) format. SinceES6 (ES2015)
,JavaScript
supports the native module format. It uses theexport
keyword to export the module's public API and theimport
keyword to import it.The System.registe
r format is designed to support ES6 modules in ES5.- The Universal Module Definition (
UMD
) format can be used in browsers andNode.js
. This is useful when a module needs to be imported by multiple different module loaders.