Package Loading Mechanism
Node.js uses CommonJs
a modular mechanism. By npm
downloading third-party packages, we introduce third-party packages into the project as follows: let xx = require('第三方包名')
, require
what is the principle and mechanism of how to load third-party packages, let’s discuss today.
require('第三方包名')
First look for third-party packages in the same directory as the module that loaded the packagenode_modules
.- Find the file in the third-party package , and find the entry module corresponding to the properties
package.json
inside , and the entry module is the loaded third-party module.main
package.json
If no file is found in the third-party package to be loaded or there ispackage.json
no attribute in the filemain
, the file in the third-party package will be loaded by defaultindex.js
.node_modules
If no folder is found in the same level directory as the file that loads the third-party module , or if none of the above conditions are found,node_modules
the folder will be searched in the parent directory of the upper level, and the search rules are the same as above.- If the disk root path of the module has not been found, an error will be reported:
can not find module xxx
.
For example:
requiere(`fs`);
It must be the system package that is loaded. Therefore, we try not to create packages with the same name as existing packages.