1. What is a module
- A file with a specific function is a module
- Module advantages: with modules, we can use these modules very easily, because modules always complete a specific function, if you want to modify the module in the function, then only need to modify the module file, module independent of each file, does not affect the module code. Modules are independent of each file and do not affect module code
- Modules are independent of each other, and if one module introduces another module, we need to expose those values in the imported module to use them
2. The modular
-
Encapsulate a complex program into several modules (files) according to certain rules (specifications) and combine them together. The internal data realization of each module is private, but it exposes some interfaces (methods) to communicate with other external modules
-
Projects developed with modular thinking are also known as modular development
-
Development of modularity
① Global development mode
Function foo(){} function bar(){} function foo(){} function bar(){} function foo(){} function bar(){Copy the code
② Namespace
Simply encapsulate the code to reduce the number of global variables
Var Namespac = {foo: function(){}, bar: function(){}Copy the code
③ IIFE mode: is a JavaScript function that executes immediately when it is defined.
var Module = (function(){ var foo = function(){ } return { foo: foo } })() Module.foo() Copy the code
3. Why modularity
-
Reduce complexity
-
Improve decoupling
-
The deployment of convenient
4. Benefits of modularity
- Avoid naming conflicts (reduce namespace contamination)
- Better classification, load on demand
- Higher reusability
- High maintainability
5. Module specification
- CommenJS specification, the specification adopted by Node.js
- AMD
- CMD
- ESModule(ES Modular)
6. Node.js modularization
- Commonjs module system is adopted
- Import module: require global function
- Exports module: module.exports
- The require method must be prefixed with a drive letter if it imports a local file component, even if it is in the same directory
- Node provides a Module builder, and all modules are instances of the Module
7. The module object
- module.id
The module’s identifier, usually the module’s file name with an absolute path
- module.filename
The file name of the module, with an absolute path
- module.loaded
Returns a Boolean value indicating whether the module has finished loading
- module.parent
Returns an object representing the module that called the module
- module.children
Returns an array representing other modules used by this module
- Module. exports indicates the value that the module exports
8. Exports variable
-
For convenience, Node provides an exports variable for each module, pointing to module.exports, which is equivalent to a line of commands in the header of each module (just equivalent, but not really code for that line).
var exports = module.exports
-
You can’t point an exports variable directly to a value because that breaks the link between exports and module.exports
Let student = {name:' exports.name ', age:18} exports.student = student; // Add methods to exports objects when exporting module interfaces. exports.eara = function(r){ return Math.PI*r*r; } exports.circumference = function(r){ return 2*Math.PI*r; Exports = function(x){console.log(x); // exports = function(x){console.log(x); // exports = function(x){console.log(x); // exports = function(x){console.log(x); // exports = function(x){console.log(x); }Copy the code
var aa = require('./common') console.log(aa.name); var bb = aa.student console.log(bb); var box = aa.eara(5) console.log(box); var box2 = aa.circumference(2) console.log(box2); var f = aa console.log(aa); Copy the code
9. The require instructions
- The basic function of the require command is to read and execute a JavaScript file and then return the exports object of that module, or an empty object if no specified module is found
- The require command is used to load a file. The default suffix is.js. Depending on the format of the parameter, the require command goes to different paths to find the module file
- If the argument string begins with a “/”, it means that a module file is loaded in an absolute path
require('/user/cors/fun.js')
- If the argument character begins with a “./”, it indicates that a module file is being loaded in a relative path (compared to where the script is currently executing)
require('./fun.js')
- If the argument string does not start with a “./” or a “/”, it is loaded with either a core module provided by default (in Node’s system installation directory) or an installed module (global or local) in each node_modules directory
- Usually, we would place related files in a directory for easy organization, so it would be a good idea to set up an entry file for that directory, and let the require method load the entire directory from that entry file. When require finds that the parameter string points to a directory, it automatically looks at that directory’s package.json file and loads the entry file specified by the main field.
10. Cache of modules
-
Node caches a module the first time it is loaded, and then fetches its module.exports property directly from the cacheIn the code above, the require command is used three times to load the same module. The second load adds a message attribute to the output object, but the third load still has the message attribute, which proves that the require command is not reloading the module file, but instead printing the cache.
-
If you want to execute a module more than once, you can have the module output a function, and then re-execute the output function each time you require the module
-
All cached modules are stored in require.cache. If you want to remove the cache of a module, you can write it as follows
-
Note that modules are identified by absolute path in the cache. If the module name is the same, but stored in a different path, the require command will reload the module
11. The environment variable NODE_PATH
- When node executes a script, it first looks at the environment variable NODE_PATH, which is a set of absolute paths separated by colons. If the specified module cannot be found elsewhere, NODE_PATH can be added to.bashrc
12. Cyclic loading of modules
-
If cyclic loading of modules occurs, where A loads BOTH B and B loads A, THEN B will load an incomplete version of A
-
The require method has a main attribute that can be used to determine whether the module is executing directly or by calling it
- When executed directly, the require.main attribute points to the module itself (Node module.js)
require.main === module
- When the call executes, return false(by requiring the execution)
13. Operation mechanism of the module
- Commonjs module loading mechanism
The input is a copy of the output value, that is, once a value is output, changes in the module do not affect that value (only ordinary values, if they are referential values, will be affected).
14. Require’s internal processing process
-
The require command is used to load other modules in the CommonJS specification. It is not a global command, but points to the module.require command of the current module, which in turn calls the internal Node command module._load
Step 4, execute the script for the specified module using module.pile ()
In steps 1 and 2, the require function performs the following:
- Require (): Loads external modules
- Require.resolve (): Resolves the module name to an absolute path
- Require. main: points to the main module
- Require. cache: a module that points to all caches
- Require. extensions: Calls different execution functions depending on the file name extension