从 node_modules 文件夹加载


【Loading from node_modules folders】

如果传递给 require() 的模块标识符不是一个核心模块,并且不以 '/''../''./' 开头,则 Node.js 会从当前模块的目录开始,添加 /node_modules,并尝试从该位置加载模块。Node.js 不会向已以 node_modules 结尾的路径追加 node_modules

【If the module identifier passed to require() is not a core 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.】