nodeJS模块寻址规则

引子

阮一峰一则教程中, 将应用放置在  npm 模块安装目录同等级的目录(https://github.com/ruanyf/webpack-demos)下。

 

但是应用目录文件中, 引用标准库的使用方法没有变化

https://github.com/ruanyf/webpack-demos/blob/master/demo15/index.js

 

如下代码

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Switch, Route, Link } from 'react-router-dom';

 

NodeJS的寻址规则是怎么样的呢?

尽管这个是前端的代码, 但是我们知道实际上引用模块,并打包的动作, 是交给 webpack来的做得,

模块的寻址规则, 则是按照NodeJS的文件寻址规则, 没有改变,而是打包后, 变成前端可执行的集成代码。

 

寻址规则

https://nodejs.org/api/modules.html#modules_accessing_the_main_module

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)
4. LOAD_NODE_MODULES(X, dirname(Y))
5. THROW "not found"

LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text.  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. let M = X + (json main field)
   c. LOAD_AS_FILE(M)
   d. LOAD_INDEX(M)
2. LOAD_INDEX(X)

LOAD_NODE_MODULES(X, START)
1. let DIRS = NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
   a. LOAD_AS_FILE(DIR/X)
   b. 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

 

 下面两个寻址方式很明确

1、 core library , nodejs实现的标准库,

2、 绝对和相对路径,

 

对于第三方库(通过npm安装的) node_modules文件夹下管理的库,

则拥有一套精心设计的寻址规则:

1、 按照当前路径下, 寻找 node_modules/xxx

2、 递归上升上级路径下, 寻找node_modules/xxx

。。。。

3、 在全局环境路径下找 .node_modules/xxx

 

转载于:https://www.cnblogs.com/lightsong/p/10540419.html

你可能感兴趣的:(nodeJS模块寻址规则)