This is the 15th day of my participation in the August Text Challenge.More challenges in August

The CommonJS module outputs a shallow copy of the value

The CommonJs module outputs a copy of the value, meaning that once a value is output, changes within the module do not affect that value.

// common.js
var count = 1;

var printCount = () = >{ 
   return ++count;
}

module.exports = {
     printCount: printCount,
     count: count
};
 // index.js
let v = require('./common');
console.log(v.count); / / 1
console.log(v.printCount()); / / 2
console.log(v.count); / / 1
Copy the code

You can see that common.js has changed the count, but the output remains the same. This is because count is a primitive type and is cached. You have to write it as a function to get the value of the internal variation. Module. exports in common.js

module.exports = {
     printCount: printCount,
     get count() {return count
     }
};
// the output is 1,2,2
Copy the code

The ES6 module outputs references to values

In ES6, it is written like this, using export and import.

// es6.js
export let count = 1;
export function printCount() {
     ++count;
}
// main1.js
import  { count, printCount } from './es6';
console.log(count)
console.log(printCount());
console.log(count)
// the output is 1,2,2
Copy the code

ES6 modules are referenced dynamically and do not cache. The contents of a module are bound to the module in which they are located. Values are loaded dynamically and cannot be copied. Export default in ES6:

let count = 1;
 function printCount() {
     ++count;
} 
export default { count, printCount}
// main3.js
import res form './main3.js'
console.log(res.count)
Copy the code

conclusion

The CommonJS module prints a shallow copy of the value, the ES6 module prints a reference to the value.

The CommonJS module is run time loaded, and the ES6 module is compile time output interface.

CommonJS loads an object (that is, the module.exports property) that is generated only after the script runs. An ES6 module is not an object, and its external interface is a static definition that is generated during the code static parsing phase.

The CommonJS module require() is a synchronously loaded module, while the ES6 module import command is asynchronously loaded, with a separate module-dependent parsing phase.