webpack dllplugin的使用姿勢

之前在上家公司,主要負責(zé)系統(tǒng)后臺的業(yè)務(wù),由于業(yè)務(wù)代碼較冗余,一直在嘗試使用webpack dllplugin,由于業(yè)務(wù)線的耽誤,一直沒有時間優(yōu)化,今天有時間,重新梳理了一下,整理一下,分享給大家,webpack dllplugin的正確姿勢

part I:webpack dllplugin的配置

  1. 配置一份webpack配置文件,用于生成動態(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是動態(tài)庫輸出的模塊全局變量名稱。注意,這個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,就會默認生成上述格式的文件。
vendor-manifest.json文件如下:

{"name":"vendor_868ab5aa63db7c7c0a32","content":{"./node_modules/process/browser.js":{"id":0,"meta":{}},

也就是說,這里是一種對應(yīng)的關(guān)系,只用vendor-manifest文件中的name與真正的變量一致,才能被找到。

  1. 使用動態(tài)鏈接庫,黃金搭檔DllReferencePlugin。
new DllReferencePlugin({
  // 描述 react 動態(tài)鏈接庫的文件內(nèi)容
  manifest: require('../dist/site/vendor-manifest.json'),
})
  1. 引用文件。
    這一步,經(jīng)常會被忘記。一定要在HtmlWebpackPlugin的template 模版html文件中,手動引入dll_vendor.js文件。
<body>
    <div id="app"></div>
    <script src="./dll_vendor.js"></script>
</body>

經(jīng)過上述三個步驟后,就大功告成了。無論是正式環(huán)境build,還是webpack-dev-server都能引用dll文件。

part II:簡單分析源碼

這里是really 簡單分析,不深入探討,后續(xù)會陸續(xù)輸出webpack的系列文章,再具體討論每個plugin的實現(xiàn)細節(jié)。

很明顯,只涉及了webpackDllPlugin以及webpackReferencePlugin,那么這一part的研究對象就是這兩位了。

  1. 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用于生成對應(yīng)的manifest.json文件。

  1. 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是作為外部依賴,不進行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)化,使用于將項目依賴的基礎(chǔ)模塊(第三方模塊)抽離出來,然后打包到一個個單獨的動態(tài)鏈接庫中。當(dāng)下一次打包時,通過webpackReferencePlugin,如果打包過程中發(fā)現(xiàn)需要導(dǎo)入的模塊存在于某個動態(tài)鏈接庫中,就不能再次被打包,而是去動態(tài)鏈接庫中g(shù)et到。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容