Usage and difference between CommonJS and ES6 MODULE

CommonJS usage

Note: exports, not exports

export

 //Through module Exports exports an object that stores function functions or data or a specific value
//When importing, use the user-defined variable obj FN1 () can be used
module.exports = { 
  fn1: function () {
    console.log("fn1")
  },
  flag: true,
  arr: [],
}

//You can also export directly through exports, which is essentially a module implemented by node Exports is short for VAR exports = module exports
exports.fn2 = function () {
  console.log("fn2")
}

function mod1(){console.log(1);}
function mod2(){console.log(2);}
module.exports={mod1:mod1,mod2:mod2}

introduce

const express = require("express")      //express is a third-party module of node. You can directly import the module name

const obj = require("Module file path")       // When importing a user-defined module, the parameter of the require function is the file path of the module. The module file is introduced and assigned to the user-defined variable obj 

var {mod1,mod2} = require('./t');

ES6 MODULE usage

export

First kind - Direct export
export var firstName = 'Michael';
export function multiply(x, y) { return x * y;};

Second - use{}export
export { firstName, multiply };

Note: neither export 1 nor M can be exported directly

// report errors
export 1;

// report errors
var m = 1;
export m;

correct
// Writing method I
export var m = 1;

// Writing method 2
var m = 1;
export {m};

// Writing method III
var n = 1;
export {n as m};

introduce

import { firstName, lastName, year } from './profile.js';

alias
import { lastName as surname } from './profile.js';

Note: it is not allowed to rewrite the interface in the script of loading the module.

It can be directly understood that what is introduced through ES6 MODULE is declared with const.

import {a} from './xxx.js'
a = {}; // Syntax Error : 'a' is read-only;
a.foo = 'hello'; // Legal operation

Note: if you want to input the default method and other interfaces in an import statement, you can write it as follows.

Write in parentheses first and then write in parentheses

import _, { each, forEach } from 'lodash';

Use of export default

// first group
export default function crc32() { // output
  // ...
}

import crc32 from 'crc32'; // input

// Group 2
export function crc32() { // output
  // ...
};

import {crc32} from 'crc32'; // input

The export default command can also be used before non anonymous functions.

non-anonymous 
export default function foo() {
  console.log('foo');
}
anonymous
export default function () {
  console.log('foo');
}

Compound writing of export and import

export { foo, bar } from 'my_module';

// It can be simply understood as
import { foo, bar } from 'my_module';
export { foo, bar };

CommonJS and ES6 MODULE differences

  1. The CommonJS module outputs a copy of the value, while the ES6 module outputs a reference to the value.
  2. CommonJS module is run-time loading (dynamic loading), and ES6 module is compile time output interface (static loading).
  3. The require() of CommonJS module is a synchronous loading module, and the import command of ES6 module is asynchronous loading. There is an independent module dependent parsing stage.

ES2020 supports dynamic import, details

Dynamic loading will get a promise object, and await is also supported, so on-demand loading (lazy loading) can be realized

import Static import
import xxx from 'xxx.js'
import {xx,x} from 'xxx.js'

import Dynamic import
import(xxx.js)

The difference between dynamic import and static import

import is executed in the static parsing phase, so it is the earliest execution in a module, while the dynamic one is requested when the code is executed.

CommonJS loads an object (i.e. module.exports attribute), which will not be generated until the script is run, that is to say, the module can be determined only after all the code is run Integrity of exports. The ES6 module is not an object. Its external interface is just a static definition, which will be generated in the static analysis stage of the code (loaded on demand).

The difference between a copy of a value and a reference to a value

Both import and require execute the code once, but one is executed at runtime (delaying time) and the other is parsed at compile time (importing on demand and optimizing the running speed).

When the required contents are introduced in both methods, whether as a whole or using {} to select parts, the CommonJS module outputs a copy of the value. After running the module, the value will be cached locally. Note that the original type value will be cached and the function will not be cached locally, so when executing, you still need to go to the memory to find the original storage location, In this way, the contents of the module can be changed. Otherwise, a code that changes the contents of the module as the following code is written in time. However, since the function is also copied to the new memory, the value in the module that needs to be changed cannot be found. That means that the module is dead and cannot be changed, but this is not the case. In other words, once a value is output, changes within the module will not affect the value, unless the method just mentioned is adopted.

CommonJS gets the value after the module changes

You need to use a value function, otherwise you will get the cached value all the time.

// lib.js
var counter_num = 3;
function incCounter() {counter_num++;}
function counter() {return counter_num}
module.exports = {counter,incCounter,};

var mod = require('./lib');
console.log(mod.counter());  // 3
mod.incCounter();
console.log(mod.counter()); // 4

ES6 is like injecting the selected code in the import file into the imported file. When JS engine statically analyzes the script, it will generate a read-only reference when it encounters the module loading command import. Wait until the script is actually executed, and then get the value in the loaded module according to the read-only reference.

In other words, the import of ES6 is a bit like the "symbolic connection" of Unix system. When the original value changes, the value loaded by import will also change. Therefore, the ES6 module is dynamically referenced and will not cache values. The variables in the module are bound to the module in which they are located.

Keywords: Javascript

Added by WendyLady on Sat, 05 Mar 2022 21:59:16 +0200