Contents

About JavaScript module system comparison

   Jan 29, 2024     1 min read

outline

In JavaScript, the module system plays an important role in organizing and reusing code.

CommonJS and ES Module are the two main implementations of these module systems. Let’s learn about the characteristics and differences of each.

CommonJS (require)

characteristic

  • Synchronous loading: Loads modules synchronously through the require function.
  • Runtime loading: Modules are loaded dynamically at runtime.
  • Object-based: A module is represented as an object, and you use the properties or methods of that object to access elements of the exported module.
  • Server side (Node.js): Mainly used on the server side and supported by default in the Node.js environment.

Example of use

const fs = require("fs");
const utils = require("./utils");

// use module
console.log(utils.add(2, 3));

ES Module (import/export)

characteristic

  • Asynchronous loading: Modules are loaded asynchronously. The import statement operates asynchronously and returns a promise.
  • Static loading: Modules are loaded statically, and are loaded before the code is executed.
  • Object-based: You can export or import specific parts of a module using the export and import statements.
  • Browser and server side: Supported by the latest browsers, ES Module can also be used in Node.js.

Example of use

// export module
//utils.js
export function add(a, b) {
  return a + b;
}

// import module
//main.js
import { add } from "./utils";

// use module
console.log(add(2, 3));

conclusion

CommonJS is mainly used on the server side (Node.js), while ES Module can be used on both the server and client sides.

CommonJS is synchronous loading and supports runtime loading, while ES Module is asynchronous loading and performs static loading.

CommonJS uses module.exports and require to define and import modules, while ES Module uses export and import.

The choice of modular system depends on the environment and use case, and the appropriate method should be selected according to the requirements of the project.