之前在上家公司计盒,主要負(fù)責(zé)系統(tǒng)后臺(tái)的業(yè)務(wù)蛤奥,由于業(yè)務(wù)代碼較冗余亏拉,一直在嘗試使用webpack dllplugin赶舆,由于業(yè)務(wù)線的耽誤,一直沒有時(shí)間優(yōu)化生巡,今天有時(shí)間,重新梳理了一下,整理一下描滔,分享給大家,webpack dllplugin的正確姿勢(shì)
part I:webpack dllplugin的配置
- 配置一份webpack配置文件踪古,用于生成動(dòng)態(tài)鏈接庫含长。例如,我們命名為webpack.dll.config.js.
const rootPath = path.resolve(__dirname, '../');
const isPro = process.env.NODE_ENV === 'production';
module.exports = {
entry: {
vendor: ['react', 'react-dom']
},
output: {
path: path.join(rootPath, 'dist/site'),
filename: 'dll_[name].js',
library: "[name]_[hash]"
},
plugins: [
new webpack.DllPlugin({
path: path.join(rootPath, "dist/site", "[name]-manifest.json"),
name: "[name]_[hash]"
})
]
}
這里output里的filename就是生成的文件名稱伏穆,這里也就是dll_vendor.js.而library是動(dòng)態(tài)庫輸出的模塊全局變量名稱拘泞。注意,這個(gè)library一定要與webpack.DllPlugin配置中的name完全一樣枕扫。為什么呢陪腌?
看一下,生成的manifest文件以及dll_vendor文件就明白了烟瞧。
dll_vendor.js文件如下:(這里為了清晰诗鸭,沒有壓縮)
var vendor_868ab5aa63db7c7c0a32 =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
注意library的作用,見官網(wǎng)参滴。配置了library强岸,就會(huì)默認(rèn)生成上述格式的文件。
vendor-manifest.json文件如下:
{"name":"vendor_868ab5aa63db7c7c0a32","content":{"./node_modules/process/browser.js":{"id":0,"meta":{}},
也就是說砾赔,這里是一種對(duì)應(yīng)的關(guān)系蝌箍,只用vendor-manifest文件中的name與真正的變量一致,才能被找到过蹂。
- 使用動(dòng)態(tài)鏈接庫十绑,黃金搭檔DllReferencePlugin。
new DllReferencePlugin({
// 描述 react 動(dòng)態(tài)鏈接庫的文件內(nèi)容
manifest: require('../dist/site/vendor-manifest.json'),
})
- 引用文件酷勺。
這一步本橙,經(jīng)常會(huì)被忘記。一定要在HtmlWebpackPlugin的template 模版html文件中脆诉,手動(dòng)引入dll_vendor.js文件甚亭。
<body>
<div id="app"></div>
<script src="./dll_vendor.js"></script>
</body>
經(jīng)過上述三個(gè)步驟后,就大功告成了击胜。無論是正式環(huán)境build亏狰,還是webpack-dev-server都能引用dll文件。
part II:簡(jiǎn)單分析源碼
這里是really 簡(jiǎn)單分析偶摔,不深入探討暇唾,后續(xù)會(huì)陸續(xù)輸出webpack的系列文章,再具體討論每個(gè)plugin的實(shí)現(xiàn)細(xì)節(jié)。
很明顯策州,只涉及了webpackDllPlugin以及webpackReferencePlugin瘸味,那么這一part的研究對(duì)象就是這兩位了。
- webpackDllPlugin够挂。
首先旁仿,我們已經(jīng)知道,webpackDllPlugin的作用就是做了兩件小事:根據(jù)entry孽糖,生成一份vendor文件枯冈;生成一份manifest.json文件。
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DllEntryPlugin = require("./DllEntryPlugin");
const LibManifestPlugin = require("./LibManifestPlugin");
const FlagInitialModulesAsUsedPlugin = require("./FlagInitialModulesAsUsedPlugin");
class DllPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.plugin("entry-option", (context, entry) => {
function itemToPlugin(item, name) {
if(Array.isArray(item))
return new DllEntryPlugin(context, item, name);
else
throw new Error("DllPlugin: supply an Array as entry");
}
if(typeof entry === "object" && !Array.isArray(entry)) {
Object.keys(entry).forEach(name => {
compiler.apply(itemToPlugin(entry[name], name));
});
} else {
compiler.apply(itemToPlugin(entry, "main"));
}
return true;
});
compiler.apply(new LibManifestPlugin(this.options));
compiler.apply(new FlagInitialModulesAsUsedPlugin());
}
}
module.exports = DllPlugin;
其中LibManifestPlugin用于生成對(duì)應(yīng)的manifest.json文件办悟。
- webpackReferencePlugin尘奏。
源碼片段如下,我添加了核心的兩處注釋:
compiler.plugin("before-compile", (params, callback) => {
const manifest = this.options.manifest;
if(typeof manifest === "string") {
// 將manifest加入到依賴dependency中
params.compilationDependencies.push(manifest);
// 讀取manifest.json的內(nèi)容
compiler.inputFileSystem.readFile(manifest, function(err, result) {
if(err) return callback(err);
params["dll reference " + manifest] = JSON.parse(result.toString("utf-8"));
return callback();
});
} else {
return callback();
}
});
compiler.plugin("compile", (params) => {
let manifest = this.options.manifest;
if(typeof manifest === "string") {
manifest = params["dll reference " + manifest];
}
const name = this.options.name || manifest.name;
const sourceType = this.options.sourceType || (manifest && manifest.type) || "var";
const externals = {};
const source = "dll-reference " + name;
externals[source] = name;
//將manifest的文件依賴,以external形式打包(external是作為外部依賴誉尖,不進(jìn)行pack的)
params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(sourceType, externals));
params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin({
source: source,
type: this.options.type,
scope: this.options.scope,
context: this.options.context || compiler.options.context,
content: this.options.content || manifest.content,
extensions: this.options.extensions
}));
});
part III:總結(jié)
webpack DllPlugin優(yōu)化罪既,使用于將項(xiàng)目依賴的基礎(chǔ)模塊(第三方模塊)抽離出來,然后打包到一個(gè)個(gè)單獨(dú)的動(dòng)態(tài)鏈接庫中铡恕。當(dāng)下一次打包時(shí)琢感,通過webpackReferencePlugin,如果打包過程中發(fā)現(xiàn)需要導(dǎo)入的模塊存在于某個(gè)動(dòng)態(tài)鏈接庫中探熔,就不能再次被打包驹针,而是去動(dòng)態(tài)鏈接庫中g(shù)et到。