webpack dllplugin的使用姿勢

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

part I:webpack dllplugin的配置

  1. 配置一份webpack配置文件,用于生成動態鏈接庫。例如,我們命名為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是動態庫輸出的模塊全局變量名稱。注意,這個library一定要與webpack.DllPlugin配置中的name完全一樣。為什么呢?
看一下,生成的manifest文件以及dll_vendor文件就明白了。

dll_vendor.js文件如下:(這里為了清晰,沒有壓縮)

var vendor_868ab5aa63db7c7c0a32 =
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

注意library的作用,見官網。配置了library,就會默認生成上述格式的文件。
vendor-manifest.json文件如下:

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

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

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

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

part II:簡單分析源碼

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

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

  1. webpackDllPlugin。
    首先,我們已經知道,webpackDllPlugin的作用就是做了兩件小事:根據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用于生成對應的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的內容
        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:總結
webpack DllPlugin優化,使用于將項目依賴的基礎模塊(第三方模塊)抽離出來,然后打包到一個個單獨的動態鏈接庫中。當下一次打包時,通過webpackReferencePlugin,如果打包過程中發現需要導入的模塊存在于某個動態鏈接庫中,就不能再次被打包,而是去動態鏈接庫中get到。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容