Modular
In order to resolve dependencies between files, modular specification is a good agreement.
The modular specification is a plain text of the agreement, the developers have to write code to the specifications, reduce communication costs, a great convenience to call each other between the modules.
First, understand CommonJS specification
Action: is a Javascript modular specification, the predetermined characteristics of the module and how the interdependence between the modules ;
Uses: Node.js CommonJS specifications are used;
Features: Synchronous load module; not suitable for use in the browser; browser using the AMD / CMD.
CommonJS specification defines what: Wiki description for Modules
4.1 如何引入 In a module, there is a free variable "require", that is a Function.
4.2 如何暴露给别人使用In a module, there is a free variable called "exports", that is an object that the module may add its API to as it executes.
4.3 必须有一个变量module 。In a module, there must be a free variable "module", that is an Object.
Second, the module scope and global scope
There are two scopes Node.js, are global scope and the module scope ;
- Global scope: the use of global access, similar to the browser window ;
- Each Javascript file is a separate module, each module has its own independent scope, therefore: the module members, the default can not be accessed by other modules.
- Default Node, the method defined in each of the JS file, variables belong module scope.
Mount to global
var b = 20;
global.b = b;
global.say = function () {
console.log('这是挂载到全局的 say 方法');
}
Reproduced in: https: //www.jianshu.com/p/6fb38b916cd9