Make a summary every day, persistence is victory!

/** @date 2021-06-16 @description The difference between ESM(ES6Module) and CommonJS (CJS) */Copy the code

One (sequence)

Before ES6, JS has not had its own module system, which is not friendly to the development of large projects, so the community appeared CommonJS and AMD (I am not familiar with), CommonJS is mainly used for server (Node), AMD is mainly used for browser.

But ES6 introduces ESM, and here JS finally has its own modular architecture that can almost completely replace CJS and AMD.

Here’s a quick summary of ESM and the differences between ESM and CJS.

Ii (ESM Use)

ESM is an ESModule. It is an ESModule of ECMAScript. Introduced in ES6, ESM is mainly used as follows:

Export const obj = {name: 'E1e'}; Export default {name: 'E1e'}; Import {obj} from './test.js'; Import obj from './test.js';Copy the code

Iii. (CJS use)

CJSCommonJS, mainly used on the server side, mainly used as follows:

Const obj = {a: 1}; module.exports = obj; // introduce const obj = require('./test.js');Copy the code

Iv. (Distinction)

  1. Different ways of use (above);
  2. The ESM output isThe value of the reference, and CJS outputsA copy of the value;

ESM:

// a.mjs export let age = 18; export function addAge() { age++; } // b.mjs import { age, addAge } from "./a.mjs"; addAge(); console.log(age); / / 19Copy the code

CJS:

// a.js let age = 18; // a.js let age = 18; module.exports = { age, addAge: function () { age++; }}; // b.js const { age, addAge } = require("./a.js"); addAge(); console.log(age); / / 18Copy the code

As you can see from the above example, when the ESM calls a method to modify a value in the module, the reference to that value also changes; CJS does not change after a method is called; Because CJS prints a copy of a value, ESM prints a reference to a value.

Because the ESM is a reference to the output value, it is not allowed to directly modify the value externally (except for object modification or new attribute). Otherwise, an error will be reported.

  1. The output of CJS isRun time loadingAnd the ESMCompile timeOutput interface;
Because CJS outputs an object that needs to be generated after the script runs, ESM output is static and generated at compile time.Copy the code
  1. CJS isSynchronous loadingThe ESM isAsynchronous loading;
Because CJS is a module system for the server side, the modules that need to be loaded are local, so synchronous loading is not a problem. However, when ESM is used for the browser side, some asynchronous requests may be involved, so asynchronous loading is required.Copy the code