有没有人有关于 Node 的 require 路径如何工作的明确列表?

Does anyone have a definitive list of how Node's require paths work?

我看到以下...

'./folder/'
'../folder/'
'folder/'
'/folder/'

谁能解释一下不同的路径类型?还有一种方法可以自动搜索所有文件夹吗?重构是一件痛苦的事!

如果找不到确切的文件名,那么节点将尝试加载所需的文件名,并添加扩展名 .js.json,然后是.node.

.js 文件被解释为 JavaScript 文本文件,.json 文件被解析为JSON 个文本文件。 .node 文件被解释为加载了 dlopen.

的已编译插件模块

以“/”为前缀的模块是文件的绝对路径。例如,require('/home/marco/foo.js') 将加载位于 /home/marco/foo.js.

的文件

前缀为'./'的模块是相对于调用require()的文件而言的。也就是说,对于 require('. /circle') 找到它。

没有前导 '/''./' 来指示文件,模块是 "core module" 或从 node_modules 文件夹加载。

如果给定路径不存在,require() 将抛出错误,其 code 属性 设置为'MODULE_NOT_FOUND'

摘自https://nodejs.org/api/modules.html#modules_file_modules

查看文档:https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

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.