webpack dllplugin的使用姿势

6,023 阅读3分钟
原文链接: www.jianshu.com

之前在上家公司,主要负责系统后台的业务,由于业务代码较冗余,一直在尝试使用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到。