关于node中require的查找规则
OneWord 2021-01-20 node
# 一、当require()中传入的是核心模块
如path,http等核心模块
const path = require("path")
//则会直接返回核心模块并停止查找
1
2
2
# 二、当require()中传入的是文件路径
# 会根据路径格式进行查找,但分为两种情况:
1.路径最后文件写了后缀名
const foo = require("./xxxx/xxx/xx.js")
//这会直接根据后缀名查找文件
1
2
2
2.路径最后文件没有写后缀名
const foo = require("./xxxx/xxx/xx")
/* node内部会根据以下规则进行查询
1.直接查找文件xx
2.查找xx.js文件
3.查找xx.json文件
4.查找xx.node文件
如果并未查询到文件,则会将xx作为一个目录
按照以下规则查找文件
1.查找xx/index.js文件
2.查找xx/index.json文件
3.查找xx/index.node文件
如果还是没有找到,那将会报错... */
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 三、require()中传入的即不是核心模块,也不是路径
const foo = require("xx")
/* 会现在当前路径下的node_module中寻找xx
如果找不到,去该文件上一层的node_module中寻找
逐步查找到根目录,直到找到,
找不到则报错... */
1
2
3
4
5
2
3
4
5