• The commonJs module prints a copy of the value, the ES6 module prints a reference to the value

The CommonJS module outputs a copy of the value, meaning that once it is output, internal changes do not affect the output value. Take a look at the following example

main.js
  var counter = 3;
  function incCounter() {
    counter++;
  }
  module.exports = {
    counter: counter,
    incCounter: incCounter,
  };
Copy the code

The code above outputs the counter variable and overwrites the internal method incCounter for the variable

index.js
var mod = require('./main.js');

console.log(mod.counter);  / / 3
mod.incCounter();
console.log(mod.counter); / / 3
Copy the code

After main.js is loaded, the internal changes do not affect the external output value, the internal output value will be cached, the next time the call will go through the cache.

// This is how commonJS source code handles caching
if(Module._cache[filename]){ // exports can be exported if the value exists
   return Module._cache[filename].exports;
}
Copy the code

The only way to get the internal value of commonJS is as a function

var counter = 3;
function incCounter() {
  counter++;
}
module.exports = {
  get counter () {
    return counter
  },
  incCounter: incCounter,
};
Copy the code

The above code outputs a valuer, and then executing index.js correctly reads the change of the internal variable.

index.js
3
4
Copy the code

The ES6 module outputs references to values. When the JS engine encounters the module loading import command during static parsing of the script, it will generate a read-only reference. When the script is actually executed, it will value values in the loaded module according to this read-only reference.

test.js
var userName = '0000';
function sayHi() {
	userName = '313131'
}
export {userName, sayHi};

index.js
import {userName ,sayHi} from './test.js';
	
console.log(userName); / / 3
 sayHi();
console.log(userName); / / 4
Copy the code

In the above code, the ES6 module outputs a reference to a value. The result of the run is not cached, but the value is dynamically fetched from the loaded module

  • Esmodules cannot be placed in code blocks, only in top-level scope.
  • The import of esModule (); CommonJS require is loaded asynchronously.
  • The commonJS module is run time loaded, and the ES6 module is compile time output interface.