First, understand that the CommonJS module specification and ES6 module specification are completely different concepts.
The module exports and exports
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.
module.exports = {};
Copy the code
1.module.exports
Example: example. Js
var x = 5; module.exports.x = x; Module.exports.Name=" I am a computer "; Module.exports.Say=function(){console.log(" I can do anything "); }Copy the code
Require loading modules
var example = require("./example.js"); Example.x // This value is 5 example.name // this value is "I am a computer" example.say () // this is a direct call to the Say method, printed "I can do anything"Copy the code
2. With the module exports. Exports
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;
The difference between:
Module. Exports exports to memory blocks, not exports. Exports is only a reference to module.exports, which assists the latter in adding content. To avoid confusion, try to export all module. Exports and then import them with require.
Module. exports=function(){var a="Hello World" return a; } exports cannot be exported because it breaks the link between exports and module.exports. Exports =function(){var a="Hello World" return a; // exports=function(){var a="Hello World" return a; }Copy the code
Difference between export and Export default
- Export and export default can be used to export constants, functions, files, and modules
- In a file or module, there can be more than export and import, but only one export default
- If you export the file in export mode, add {} when importing the file. Export default does not need to import the file
- Export can export variable expressions directly, export default cannot.
Example: example. Js
// export const a = '100'; Export const dogSay = function(){console.log('wang wang'); } function catSay(){console.log('miao miao'); } export { catSay };Copy the code
Export the default export
const m = 100; export default m; //export defult const m = 100; // You can't write this format here.Copy the code
Reference:
Import {dogSay, catSay} from ‘./example’;
Export default import m from ‘./example’;
Import * as exampleModule from ‘./example’;