Module system in Node
What is modularity
- File scope
- Communication rules
- Load the require
- export
Commonjs module specification
Js in Node also has a very important conceptual module system
- Module scope - use require to load modules - export module members using exports interface objectsCopy the code
Load the require
Grammar:
varCustom variable =require('modules');
Copy the code
Executes code in the loaded module to get the exports interface object in the loaded moduleCopy the code
Export exports
Node is a module scope, and all members in the default file are valid only in the module of the current file. For members that can be accessed by other modules, we need to mount the exposed members to the exports interface
Export multiple members (must be in an object) :
expotrs.a = 123;
exports.b = "wwx";
exports.c = function () {
console.log('ccc');
}
exports.d = {
foo:'bar';
}
Copy the code
Export a single member (you get numbers, strings)
module.exports = 'hello'
Copy the code
The following situations will be overridden:
module.exports = 'hello';
// The latter will override the former
module.exports = "asdasa"
Copy the code
You can also export multiple members this way
module.exports = {
add:add,
foo:foo
}
Copy the code
The principle of analytic
Exports is a reference to module.exports
//var module = {
// exports = {};
/ /}
//var exports = module.exports;
console.log(exports= = =module.exports); // => true
exports.foo = 'bar';
/ / equivalent to the
module.exports.foo = 'bar';
//return module.exports;
Copy the code
Exports. Exports
-
Each module has a Module object
-
Module objects have an exports object
-
We can mount all the members we want to export to the module.exports interface object
-
That is: mouds.exports.xxx = XXX
-
But every time moudle. Exports. XXX = XXX is very troublesome, a little bit too much
-
Exports === module. Exports result: trues
-
So for: mouds.exports. XXX = XXX the way is completely ok: expots.xxx = XXX
-
Module. exports = XXX when a module needs to export a single member, it must use: module.exports = XXX
-
Don’t use exports = XXX doesn’t work
-
Because every module eventually returns module.exports
-
Exports is just a reference to module.exports
-
So, if you reset the value of exports = xx, it will not affect Module. exports
-
Exports = module.exports