使用WebPack CommonsChunkPlugin

时间:2017-08-01 21:20:07

标签: reactjs webpack webpack-2 commonschunkplugin

我使用 WebPack CommonsChunkPlugin 来提取重复代码并减少JavaScript代码大小。我有两个html页面和两个条目。我还添加了 ReactJs 供应商条目。到目前为止,在 webpack.config.js 中我们有:

var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
    context: __dirname,
    entry: {
        react: ["react", "react-dom"],
        home: './assets/js/home.jsx',
        about: './assets/js/about.jsx',
    },

    output: {
        path: path.resolve('./assets/bundles/'),
        filename: "[name].js",
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),

        new webpack.optimize.CommonsChunkPlugin({
            name: 'react',
            minChunks: Infinity
        }),

        new BundleAnalyzerPlugin(),
    ],

    module: {
        rules: [
            {
              test: /\.jsx?$/, 
              exclude: /node_modules/,
              loader: 'babel-loader',
              options: { 
                  plugins: [["lodash", { "id": ["semantic-ui-react"] }]],
                  presets: ["es2015", "react"]
              }  
            },
        ],
    },

    resolve: {
        modules: ['node_modules', 'bower_components'],
        extensions: ['*', '.js', '.jsx']
    },
};

此配置结果使用 webpack-bundle-analyzer

webpack bundle analyzer output

如您所见,有一些重复的代码,一些在红色区域,另一些在绿色区域。我想从家里提取这些js代码,并将捆绑包提取到一个单独的包中。要提取红色区域代码,即 lodash 库,我将这些行添加到webpack配置中:

new webpack.optimize.CommonsChunkPlugin({
    name: 'lodash',
    minChunks: function(module, count) {
        return module.context.indexOf('node_modules/lodash') >= 0;
    }
}), 

但是它没有按预期工作,并且lodash库代码仍然在home和bundle中,webpack也会创建一个名为lodash的包,它几乎是空的,不包含js库。

有关如何修复它的任何想法?如何提取绿色代码?

2 个答案:

答案 0 :(得分:3)

您的问题是您正在导入每个.js/.jsx文件中的第三方库,而不先将其导入公共文件(通常称为vendor.js)。
如果您有此文件导入所有依赖项并将其作为条目包含在 CommonsChunkPlugin 中,则webpack将不再包含您的最终包中的库(home.js和{{1} })。该技术在webpack文档中称为代码拆分

vendor.js (或适合您案件的名称)

about.js

<强> webpack.config.js

import 'react';
import 'react-dom';
import 'lodash';
import 'semantic-ui-react';
//... all your npm packages

<强>的index.html

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

module.exports = {
    context: __dirname,
    entry: {
        vendor: './assets/js/vendor.js,
        home: './assets/js/home.jsx',
        about: './assets/js/about.jsx',
    },
    output: {
        path: path.resolve('./assets/bundles/'),
        filename: '[name].js',
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: Infinity
        }),
    ],

    //Rest of Your config ...
};

检查webpack代码拆分文档:

答案 1 :(得分:1)

我设法通过向插件添加一个公共块来解决问题。所以最终的webpack配置是:

var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {

    context: __dirname,

    entry: {
        react: ["react", "react-dom"],
        home: './assets/js/home.jsx',
        about: './assets/js/about.jsx',
    },

    output: {
        path: path.resolve('./assets/bundles/'),
        filename: "[name].js",
    },

    plugins: [

        new BundleTracker({filename: './webpack-stats.json'}),

        new webpack.optimize.CommonsChunkPlugin({
            name: 'react',
            filename: '[name].js',
            minChunks: Infinity,
        }),

        new webpack.optimize.CommonsChunkPlugin({
            name: 'common',
            chunks: ['home', 'about'],
            filename: '[name].js',
        }),
    ],

    module: {
        rules: [
            {
                test: /\.jsx?$/, 
                exclude: /node_modules/,
                loader: 'babel-loader',
                options: { 
                    plugins: [
                      ["lodash", { "id": ["semantic-ui-react"] }]
                    ],
                    presets: ["es2015", "react"]
                }
            },
        ],
    },

    resolve: {
        modules: ['node_modules', 'bower_components'],
        extensions: ['*', '.js', '.jsx']
    },
};

现在捆绑分析仪输出如下:

analyzer output

如图所示,常见的语义 - ui-react和lodash库现在只是普通的捆绑而不再重复。