The CommonJS module specification and ES6 module specification are two different concepts.
CommonJS module specification
Node applications are composed of modules that follow the CommonJS module specification.
According to this specification, each file is a module with its own scope. Variables, functions, and classes defined in one file are private and invisible to other files.
The CommonJS specification states that within each module, the module variable represents the current module. This variable is an object whose exports property (module.exports) is the interface to the outside world. Loading a module loads the module.exports property of that module.
var x = 5;
var addX = function (value) {
return value + x;
};
module.exports.x = x;
module.exports.addX = addX;
Copy the code
The code above exports the x variable and the function addX via module.exports.
The require method is used to load modules.
var example = require('./example.js'); console.log(example.x); // 5 console.log(example.addX(1)); / / 6Copy the code
ES6 module specifications
Unlike CommonJS, ES6 uses export and import to export and import modules.
// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
export {firstName, lastName, year};
Copy the code
It should be noted that the export command specifies the external interface and must establish a one-to-one correspondence with variables inside the module.
Export var m = 1; Var m = 1; export {m}; Var n = 1; export {n as m};Copy the code
Export the default command
// export-default.js
export default function () {
console.log('foo');
}
Copy the code
Exports and the module exports
Module.exports is preferred
For convenience, Node provides an exports variable for each module, pointing to module.exports. This equates to a line of command in the header of each module.
var exports = module.exports;
Copy the code
So we can add methods directly to exports objects to represent interfaces that export, just like we did on Module.exports.
Module. exports: Node exports from module. Exports: Node exports from module. Exports: Node exports from module.
// a.js exports = function a() {}; // const a = require('./a.js') // a is an empty objectCopy the code