Grunt,Webpack和DllPlugin

时间:2016-05-01 20:14:46

标签: javascript gruntjs webpack dllplugin dllreferenceplugin

我无法直观地了解如何在使用Grunt进行构建的同时将DllPlugin/DllReferencePlugin与Webpack结合使用。对于那些没有知识的人,DllPlugin会创建一个可以与其他包共享的单独包。它还会创建一个清单文件(重要)来帮助进行链接。然后,构建时,另一个包使用DllReferencePlugin来抓取之前创建的 DllPlugin Bundle 。为此,它需要先前创建的清单文件。

在Grunt中,这需要在grunt运行之前创建清单文件,不是吗?下面是一个简化的代码示例:

webpack.dll.js

// My Dll Bundles, which creates
// - ./bundles/my_dll.js
// - ./bundles/my_dll-manifest.json
module.exports = {

    entry: {
        my_dll : './dll.js'
    },
    // where to send final bundle
    output: {
        path: './bundles',
        filename: "[name].js"
    },
    // CREATES THE MANIFEST
    plugins: [
        new webpack.DllPlugin({
            path: "./bundles/[name]-manifest.json",
            name: "[name]_lib"
        })
    ]
};

webpack.app.js

// My Referencing Bundle, which includes
// - ./bundles/app.js
module.exports = {

    entry: {
        my_app : './app.js'
    },
    // where to send final bundle
    output: {
        path: './bundles',
        filename: "[name].js"
    },
    // SETS UP THE REFERENCE TO THE DLL
    plugins: [
        new webpack.DllReferencePlugin({
          context: '.',
          // IMPORTANT LINE, AND WHERE EVERYTHING SEEMS TO FAIL
          manifest: require('./bundles/my_dll-manifest.json')
        })
    ]
};

如果您查看第二部分 webpack.app.js ,我已经评论了grunt中的所有内容似乎都失败了。为了使DllReferencePlugin工作,它需要来自DllPlugin的清单文件,但在Grunt工作流中,grunt将在grunt本身的初始化时加载这两个配置,导致manifest: require('./bundles/my_dll-manifest.json')行失败,因为之前的grunt步骤构建webpack.dll.js尚未完成,意味着尚未存在。

1 个答案:

答案 0 :(得分:1)

var path = require("path");
var util = require('util')
var webpack = require("webpack");

var MyDllReferencePlugin = function(options){
    webpack.DllReferencePlugin.call(this, options);
}

MyDllReferencePlugin.prototype.apply = function(compiler) {
    if (typeof this.options.manifest == 'string') {
        this.options.manifest = require(this.options.manifest);
    }

    webpack.DllReferencePlugin.prototype.apply.call(this, compiler);
};


// My Referencing Bundle, which includes
// - ./bundles/app.js
module.exports = {

    entry: {
        my_app : './app.js'
    },
    // where to send final bundle
    output: {
        path: './bundles',
        filename: "[name].js"
    },
    // SETS UP THE REFERENCE TO THE DLL
    plugins: [
        new MyDllReferencePlugin({
          context: '.',
          // IMPORTANT LINE, AND WHERE EVERYTHING SEEMS TO FAIL
          manifest: path.resolve('./bundles/my_dll-manifest.json')
        })
    ]
};