从 node_modules 文件夹加载


¥Loading from node_modules folders

如果传递给 require() 的模块标识符不是 built-in 模块,并且不是以 '/''../''./' 开头,则 Node.js 从当前模块的目录开始,并添加 /node_modules,并尝试从中加载模块 地点。Node.js 不会将 node_modules 附加到已经以 node_modules 结尾的路径。

¥If the module identifier passed to require() is not a built-in module, and does not begin with '/', '../', or './', then Node.js starts at the directory of the current module, and adds /node_modules, and attempts to load the module from that location. Node.js will not append node_modules to a path already ending in node_modules.

如果在那里找不到它,则它移动到父目录,依此类推,直到到达文件系统的根目录。

¥If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.

例如,如果 '/home/ry/projects/foo.js' 处的文件调用 require('bar.js'),则 Node.js 将按以下顺序查找以下位置:

¥For example, if the file at '/home/ry/projects/foo.js' called require('bar.js'), then Node.js would look in the following locations, in this order:

  • /home/ry/projects/node_modules/bar.js

  • /home/ry/node_modules/bar.js

  • /home/node_modules/bar.js

  • /node_modules/bar.js

这允许程序本地化它们的依赖,这样它们就不会发生冲突。

¥This allows programs to localize their dependencies, so that they do not clash.

通过在模块名称后包含路径后缀,可以要求与模块一起分发的特定文件或子模块。例如,require('example-module/path/to/file') 将相对于 example-module 所在的位置解析 path/to/file。后缀路径遵循相同的模块解析语义。

¥It is possible to require specific files or sub modules distributed with a module by including a path suffix after the module name. For instance require('example-module/path/to/file') would resolve path/to/file relative to where example-module is located. The suffixed path follows the same module resolution semantics.