preface
The package manager refers to NPM, YARN, CNPM, etc. Before the package manager, if the front-end developer needed to use a library, such as jQuery, he had to go to the jQuery official website to download it locally and then import it. If he had to rely on other libraries, he would find it very troublesome and some programmers could not bear it. NPM founder ** Isaac Z. Schlueter ** offers a solution: use a tool to bring all this code together and manage it. This tool is his NPM, which stands for Node Package Manager. Whether it’s NPM, YARN, etc., the lookup rules for packages are pretty much the same. This article explains what the lookup rules were when we introduced packages.
The body of the
Loadsh: loadsh: loadsh: loadsh: loadsh: loadsh: loadsh /? Loadsh: loadsh: loadsh: loadsh: loadsh
var _ = require("loadsh");
console.log(_);
Copy the code
First, when importing a module using nodeJS, if the module path does not start with./ or.. /, node thinks the imported module is from the node_modules directory, for example:
It first looks for files from the following location in the current directory
1. node_modules/loadsh.js
2.Node_modules /lodash/ entry fileCopy the code
If no such file exists in the current directory, the system searches for it in the same way
For example, if I create a new loadsh.js file in the current folder, I won’t find the “real” loadsh.
If the file cannot be found in the top-level directory, an error is thrown
The entry files mentioned above are determined according to the following rules
-
View the package.json file of the imported package and read the main field as the entry file
-
If the main field is not included, index.js is used as the entry file
The rules for importing files also apply to modules in your own projects
Such as:
Create my own XXX package under node_modules and import it in index.js.
var _ = require("XXX");
console.log(_);
Copy the code
Why print the main module? The answer is simple, because my package.json entry file is configured with main.
If I change this field to hello.js, then the entry file is hello.js. If you don’t write the main field, it will default to index.js as the entry file.
In Node, you can also manually specify a path to import files, which is rare
var _ = require("./node_modules/XXX/hello");
console.log(_);
Copy the code
A small knowledge point, nothing good summary, we understand enough ~