CommonJS vs. ES modules

recently updated

What is a module?

A module is simply isolated code that can be exported from one file and imported to another. In JavaScript, it’s a piece of self-contained exportable code. To be modular means to be interchangeable. The entire code for that particular section of your application can be uplifted, moved and reused as needed.

As our program grows bigger, it may contain many lines of code. Instead of putting everything in a single file, you can use modules to separate codes in separate files as per their functionality. This makes our code organized and easier to maintain.

CommonJS vs. ES modules

Since the very beginning of NodeJS, the CommonJS module system is the default module system within the ecosystem. However, recently a new module system was added to NodeJS named ES module.

In NodeJS each .js file is handled as a separate CommonJS module. This means that variables, functions, classes, etc. are not accessible to other files by default. You need to explicitly tell the module system which parts of your code should be exported.

This is done via the module.exports object or the exports shortcut, which are both available in every CommonJS module. Whenever you want to import code into a file, you use the require() function.

Since the 2015 edition of the underlying ECMAScript standard (ES2015) we actually have a standardized module system in the JavaScript language itself, which is simply called ES Modules.
It took a while before the browser vendors and the NodeJS maintainers actually fully implemented the standard.

Instead of the require() function for importing modules, we now use a specific import syntax.

Also, instead of a specific module object, we now use the export keyword in front of our class declaration. This tells the compiler, which parts of the file should be accessible by other files.


Thankyou!