阮一峯一則教程中, 將應用放置在 npm 模塊安裝目錄同等級的目錄(https://github.com/ruanyf/webpack-demos)下。html
可是應用目錄文件中, 引用標準庫的使用方法沒有變化前端
https://github.com/ruanyf/webpack-demos/blob/master/demo15/index.jsnode
以下代碼react
import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter, Switch, Route, Link } from 'react-router-dom';
NodeJS的尋址規則是怎麼樣的呢?webpack
儘管這個是前端的代碼, 可是咱們知道實際上引用模塊,並打包的動做, 是交給 webpack來的作得,git
模塊的尋址規則, 則是按照NodeJS的文件尋址規則, 沒有改變,而是打包後, 變成前端可執行的集成代碼。github
https://nodejs.org/api/modules.html#modules_accessing_the_main_moduleweb
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
下面兩個尋址方式很明確npm
一、 core library , nodejs實現的標準庫,json
二、 絕對和相對路徑,
對於第三方庫(經過npm安裝的) node_modules文件夾下管理的庫,
則擁有一套精心設計的尋址規則:
一、 按照當前路徑下, 尋找 node_modules/xxx
二、 遞歸上升上級路徑下, 尋找node_modules/xxx
。。。。
三、 在全局環境路徑下找 .node_modules/xxx