Node require() 加载规则

  1. 核心模块 http,fs 等直接返回模块
  2. / 开头加载全局的文件,再加载文件夹
  3. ./ 和 ../ 开头先加载文件,再加载文件夹
  4. 非核心模块,路径里也没有 / ./ ../ 的则去 node_module 里加载文件夹

加载文件 X:X -> X.js -> X.json -> X.node

加载文件夹: X/package.json 里得到 main 字段为 M,加载文件 M。找不到再 加载文件 index

对此,node 官网文档有一段伪代码描述:

require(X) from module at path Y

1. If X is a core module,
   a. return the core module
   b. STOP
  
2. If X begins with '/'
   a. set Y to be the filesystem root

3. If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
   c. THROW "not found"

4. LOAD_SELF_REFERENCE(X, dirname(Y))

5. LOAD_NODE_MODULES(X, dirname(Y))

6. THROW "not found"

LOAD_AS_FILE(X)
1. If X is a file, load X as its file extension format.  STOP
2. If X.js is a file, load X.js as JavaScript text.  STOP
3. If X.json is a file, parse X.json to a JavaScript Object.  STOP
4. If X.node is a file, load X.node as binary addon.  STOP

LOAD_INDEX(X)
1. If X/index.js is a file, load X/index.js as JavaScript text.  STOP
2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
3. If X/index.node is a file, load X/index.node as binary addon.  STOP

LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
   a. Parse X/package.json, and look for "main" field.
   b. If "main" is a falsy value, GOTO 2.
   c. let M = X + (json main field)
   d. LOAD_AS_FILE(M)
   e. LOAD_INDEX(M)
   f. LOAD_INDEX(X) DEPRECATED
   g. THROW "not found"
2. LOAD_INDEX(X)

LOAD_NODE_MODULES(X, START)
1. let DIRS = NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
   a. LOAD_PACKAGE_EXPORTS(DIR, X)
   b. LOAD_AS_FILE(DIR/X)
   c. LOAD_AS_DIRECTORY(DIR/X)

NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let I = count of PARTS - 1
3. let DIRS = [GLOBAL_FOLDERS]
4. while I >= 0,
   a. if PARTS[I] = "node_modules" CONTINUE
   b. DIR = path join(PARTS[0 .. I] + "node_modules")
   c. DIRS = DIRS + DIR
   d. let I = I - 1
5. return DIRS

......
posted @ 2020-06-03 14:08  Ever-Lose  阅读(865)  评论(0编辑  收藏  举报