The main difference between the Commonjs module and the ES6 module is that thecommonjs module is a copy, the ES6 module is a reference , but understanding these, first understand the problem of object replication, in retrospect to understand the difference between the two modules.
One, the basic data type module
./a1.js
ES6 Module
exportvar=1;setTimeout=>=2,500);
./a2.js
COMMOJS Module
var=2;module.exports= a2;setTimeout=>=3,500);
./index.js
Output
import{}from‘./a1‘;const=require(‘./a2‘);setTimeout=>console.log(a1, a2),1000);// 2,2
Now change it../index.js
import { a1 } from ; //const A2 = require ('./a2 '); //a1 = 1;//Compile error var A2 = require () A2 = ' A2 ' ; settimeout (() => console . log (A1 A2) 1000 ) //2 ' A2 '
The conclusion is: thees6 module is a reference, and there is only a read-only state, cannot modify its variable value (said more accurate point, cannot modify its variable pointer pointing, but can change the internal pointer point, in the complex data type module will explain); Commonjs is a copy, And can modify its value (which is called the change pointer pointing), as is the deep copy also shallow copy, also will be in the complex data type module will explain .
I. Modules for complex data types
./a1.js
ES6 Module
exportconst={ name:‘lc‘, friends: [‘xm‘,‘xh‘]};setTimeout=>person.name=‘liangcheng‘,500);
./a2.js
COMMOJS Module
var={ name:‘xsz‘,// 不要猜测是谁的名字 owner: [‘lc‘]};module.exports= dog;setTimeout=>dog.name=‘xushizhou‘,500);
./index.js
Output
import{}from‘./a1‘;const=require(‘./a2‘);setTimeout=>console.log(person.name,dog.name),1000);//liangcheng xushizhou
It is concluded that both are dynamically modifying the values of their properties or elements, meaning that commonjs is a shallow copy .
To summarize:
Features of the ES6 module:
- Static, must be at the top, cannot use conditional statements, automatically adopt strict mode
- Treeshaking and compilation optimizations, and scope promotion in WEBPACK3
- External can get real-time values, not cached values (references instead of copy)
The difference between the ES6 module and the Commonjs module:
- COMMONJS module can be re-assigned to the ES6 module re-assignment will compile error
- Commonjs is a copy of the module (shallow copy), ES6 is a reference to the module (that is, the ES6 module only exists read-only, can not change its value, the point is that the pointer is not variable, like a const)
The same points of the ES6 module and the Commonjs module:
- Both can change the value of an object's internal properties
What is the difference between the Commonjs module and the ES6 module?