reactjs – 使用WebPack CommonsChunkPlugin提取重复的JavaScript代码

前端之家收集整理的这篇文章主要介绍了reactjs – 使用WebPack CommonsChunkPlugin提取重复的JavaScript代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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的配置结果:

如您所见,有一些重复的代码,一些在红色区域,另一些在绿色区域.我想从家里提取这些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库.

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

解决方法

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

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

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

webpack.config.js

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

module.exports = {
    context: __dirname,entry: {
        vendor: './assets/js/vendor.js,filename: '[name].js',plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',//Rest of Your config ...
};

的index.html

<body>
    <!-- AFTER YOUR HTML CODE -->

    <script type="text/javascript" src="/assets/bundles/vendor.js"></script>
    <script type="text/javascript" src="/assets/bundles/home.js"></script>
    <script type="text/javascript" src="/assets/bundles/about.js"></script>
</body>

检查webpack代码拆分文档:

>旧文档:https://webpack.github.io/docs/code-splitting.html#split-app-and-vendor-code
>新文件https://webpack.js.org/plugins/commons-chunk-plugin/#explicit-vendor-chunk

原文链接:https://www.f2er.com/js/156990.html

猜你在找的JavaScript相关文章