CommonJS

CommonJS is the most widely used, unofficial spec right now. CommonJS is a specification for implementing modules in Node.js. According to the CommonJS specification, every module needs to be represented by a separate file. CommonJS modules are imported synchronously. This is the reason why browsers do not use CommonJS as a module loader!

Let's see an example of how to create and import modules using CommonJS. First, we will create a file named math.js that represents a module. Here is sample code that will be inside the module:

const sum =(x, y) => x + y;const sub = (x, y) => x - y;const math = {   findSum(a, b) {     return sum(a,b);   },   findSub(a, b){     return sub(a, b);   } } exports.math = math; // or module.exports.math = math

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.