The loading mechanism of packages in npm

Package Loading Mechanism

Node.js uses CommonJsa modular mechanism. By npmdownloading third-party packages, we introduce third-party packages into the project as follows: let xx = require('第三方包名'), requirewhat is the principle and mechanism of how to load third-party packages, let’s discuss today.

  1. require('第三方包名')First look for third-party packages in the same directory as the module that loaded the package node_modules.
  2. Find the file in the third-party package , and find the entry module corresponding to the properties package.jsoninside , and the entry module is the loaded third-party module.main
  3. package.jsonIf no file is found in the third-party package to be loaded or there is package.jsonno attribute in the file main, the file in the third-party package will be loaded by default index.js.
  4. node_modulesIf 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_modulesthe folder will be searched in the parent directory of the upper level, and the search rules are the same as above.
  5. 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.

Guess you like

Origin blog.csdn.net/qq_62860882/article/details/130040844