First we need to understand a premise that the COMMONJS module specification and the ES6 module specification are completely two different concepts.
COMMONJS Module Specification
The Node application is made up of modules, using the COMMONJS module specification.
According to this specification, each file is a module that has its own scope. variables, functions, and classes defined in a file are private and not visible to other files.
The COMMONJS specification stipulates that within each module, the module variables represent the current modules. This variable is an object whose exports property (that is, module.exports) is an external interface. Loading a module is actually loading the module's Module.exports property.
var x = 5;var addX = function (value) { return value + x;};module.exports.x = x;module.exports.addX = addX;
The above code is output by module.exports the variable x and the function Addx.
The Require method is used to load the module.
var example = require(‘./example.js‘);console.log(example.x); // 5console.log(example.addX(1)); // 6
Exports and Module.exports
For convenience, node provides a exports variable for each module, pointing to Module.exports. This is equivalent to a command on each module header, one row.
var exports = module.exports;
We can then add the method directly on the exports object, representing the interface to the output, as if it were added on the module.exports. Note that you cannot directly point the exports variable to a value, as this is tantamount to cutting off the exports and module.exports connections.
ES6 Module Specification
Unlike COMMONJS,ES6, exporting and importing modules using export and import.
// profile.jsvar firstName = ‘Michael‘;var lastName = ‘Jackson‘;var year = 1958;export {firstName, lastName, year};
It is important to note that the Export command specifies an external interface and must establish a one by one correspondence with the variables inside the module.
// 写法一export var m = 1;// 写法二var m = 1;export {m};// 写法三var n = 1;export {n as m};
Export default command
Use the Export default command to specify the default output for the module.
// export-default.jsexport default function () { console.log(‘foo‘);}
Comparison of the export of ES6 and the module.exports of Nodejs