學(xué)習(xí)目標(biāo)
本質(zhì)上喳魏,webpack 是一個現(xiàn)代 JavaScript 應(yīng)用程序的靜態(tài)模塊打包器(module bundler)。當(dāng) webpack 處理應(yīng)用程序時怀薛,它會遞歸地構(gòu)建一個依賴關(guān)系圖(dependency graph)刺彩,其中包含應(yīng)用程序需要的每個模塊,然后將所有這些模塊打包成一個或多個 bundle枝恋。
通過minipack這個項目的源碼學(xué)習(xí)了解上邊提到的整個工作流程
demo目錄
.
├── example
├── entry.js
├── message.js
├── name.js
入口文件 entry.js:
// 入口文件 entry.js
import message from './message.js';
console.log(message);
message.js
// message.js
import {name} from './name.js';
export default `hello ${name}!`;
name.js
// name.js
export const name = 'world';
入口文件
入口起點(entry point)指示 webpack 應(yīng)該使用哪個模塊创倔,來作為構(gòu)建其內(nèi)部依賴圖的開始。進入入口起點后焚碌,webpack 會找出有哪些模塊和庫是入口起點(直接和間接)依賴的畦攘。
createAsset:生產(chǎn)一個描述該模塊的對象
createAsset 函數(shù)會解析js文本,生產(chǎn)一個描述該模塊的對象
function createAsset(filename) {
/*讀取文件*/
const content = fs.readFileSync(filename, 'utf-8');
/*生產(chǎn)ast*/
const ast = babylon.parse(content, {
sourceType: 'module',
});
/* 該數(shù)組將保存此模塊所依賴的模塊的相對路徑十电。*/
const dependencies = [];
/*遍歷AST以嘗試?yán)斫庠撃K所依賴的模塊知押。 為此,我們檢查AST中的每個導(dǎo)入聲明摆出。*/
traverse(ast, {
ImportDeclaration: ({node}) => {
/*將導(dǎo)入的值推送到依賴項數(shù)組中朗徊。*/
dependencies.push(node.source.value);
},
});
const id = ID++;
/* 使用`babel-preset-env`將我們的代碼轉(zhuǎn)換為大多數(shù)瀏覽器可以運行的代碼。*/
const {code} = transformFromAst(ast, null, {
presets: ['env'],
});
/*返回這個描述對象*/
return {
id,
filename,
dependencies,
code,
};
}
createGraph: 生產(chǎn)依賴關(guān)系圖
function createGraph(entry) {
// 解析入口文件
const mainAsset = createAsset(entry);
/*將使用隊列來解析每個模塊的依賴關(guān)系偎漫。 為此爷恳,定義了一個只包含入口模塊的數(shù)組。*/
const queue = [mainAsset];
/*我們使用`for ... of`循環(huán)迭代隊列象踊。 最初温亲,隊列只有一個模塊棚壁,但在我們迭代它時,我們會將其他新模塊推入隊列栈虚。 當(dāng)隊列為空時袖外,此循環(huán)將終止。*/
for (const asset of queue) {
/*我們的每個模塊都有一個它所依賴的模塊的相對路徑列表魂务。 我們將迭代它們曼验,使用我們的`createAsset()`函數(shù)解析它們,并跟蹤該模塊在此對象中的依賴關(guān)系粘姜。*/
asset.mapping = {};
// This is the directory this module is in.
const dirname = path.dirname(asset.filename);
// We iterate over the list of relative paths to its dependencies.
asset.dependencies.forEach(relativePath => {
// Our `createAsset()` function expects an absolute filename. The
// dependencies array is an array of relative paths. These paths are
// relative to the file that imported them. We can turn the relative path
// into an absolute one by joining it with the path to the directory of
// the parent asset.
const absolutePath = path.join(dirname, relativePath);
// Parse the asset, read its content, and extract its dependencies.
const child = createAsset(absolutePath);
// It's essential for us to know that `asset` depends on `child`. We
// express that relationship by adding a new property to the `mapping`
// object with the id of the child.
asset.mapping[relativePath] = child.id;
// Finally, we push the child asset into the queue so its dependencies
// will also be iterated over and parsed.
queue.push(child);
});
}
// At this point the queue is just an array with every module in the target
// application: This is how we represent our graph.
return queue;
}
通過createGraph函數(shù) 生成的依賴關(guān)系對象:
[
{ id: 0,
filename: './example/entry.js',
dependencies: [ './message.js' ],
code: '"use strict";\n\nvar _message = require("./message.js");\n\nvar _message2 = _interopRequireDefault(_message);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconsole.log(_message2.default);',
mapping: { './message.js': 1 } },
{ id: 1,
filename: 'example/message.js',
dependencies: [ './name.js' ],
code: '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\n\nvar _name = require("./name.js");\n\nexports.default = "hello " + _name.name + "!";',
mapping: { './name.js': 2 } },
{ id: 2,
filename: 'example/name.js',
dependencies: [],
code: '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nvar name = exports.name = \'world\';',
mapping: {} }
]
bundle 打包
bundle函數(shù)把上邊得到的依賴關(guān)系對象作為參數(shù)鬓照,生產(chǎn)瀏覽器可以運行的包
function bundle(graph) {
let modules = '';
graph.forEach(mod => {
modules += `${mod.id}: [
function (require, module, exports) {
${mod.code}
},
${JSON.stringify(mod.mapping)},
],`;
});
const result = `
(function(modules) {
function require(id) {
const [fn, mapping] = modules[id];
function localRequire(name) {
return require(mapping[name]);
}
const module = { exports : {} };
fn(localRequire, module, module.exports);
return module.exports;
}
require(0);
})({${modules}})
`;
// We simply return the result, hurray! :)
return result;
}
參考例子,最終生產(chǎn)的代碼:
(function (modules) {
function require(id) {
const [fn, mapping] = modules[id];
function localRequire(name) {
return require(mapping[name]);
}
const module = { exports: {} };
fn(localRequire, module, module.exports);
return module.exports;
}
require(0);
})({
0: [
function (require, module, exports) {
"use strict";
var _message = require("./message.js");
var _message2 = _interopRequireDefault(_message);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
console.log(_message2.default);
},
{ "./message.js": 1 },
],
1: [
function (require, module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _name = require("./name.js");
exports.default = "hello " + _name.name + "!";
},
{ "./name.js": 2 },
],
2: [
function (require, module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var name = exports.name = 'world';
},
{},
],
})
分析打包后的這段代碼
這是一個自執(zhí)行函數(shù)
(function (modules) {
...
})({...})
函數(shù)體內(nèi)聲明了 require
函數(shù)孤紧,并執(zhí)行調(diào)用了require(0);
require函數(shù)就是 從參數(shù)modules對象中找到對應(yīng)id的 [fn, mapping]
如果模塊有依賴其他模塊的話豺裆,就會執(zhí)行傳入的require
函數(shù),也就是localRequire
函數(shù)
function require(id) {
// 數(shù)組的解構(gòu)賦值
const [fn, mapping] = modules[id];
function localRequire(name) {
return require(mapping[name]);
}
const module = { exports: {} };
fn(localRequire, module, module.exports); // 遞歸調(diào)用
return module.exports;
}
接收一個模塊id,過程如下:
第一步:解構(gòu)module(數(shù)組解構(gòu))号显,獲取fn和當(dāng)前module的依賴路徑
第二步:定義引入依賴函數(shù)(相對引用)臭猜,函數(shù)體同樣是獲取到依賴module的id,localRequire 函數(shù)傳入到fn中
第三步:定義module變量押蚤,保存的是依賴模塊導(dǎo)出的對象蔑歌,存儲在module.exports中,module和module.exports也傳入到fn中
第四步:遞歸執(zhí)行揽碘,直到子module中不再執(zhí)行傳入的require函數(shù)
要更好了解“打包”的原理丐膝,就需要學(xué)習(xí)“模塊化”的知識。
參考: