Skip to content

Instantly share code, notes, and snippets.

@sokra
Last active May 23, 2024 16:10
Show Gist options
  • Save sokra/1522d586b8e5c0f5072d7565c2bee693 to your computer and use it in GitHub Desktop.
Save sokra/1522d586b8e5c0f5072d7565c2bee693 to your computer and use it in GitHub Desktop.

RIP CommonsChunkPlugin

webpack 4 removes the CommonsChunkPlugin in favor of two new options (optimization.splitChunks and optimization.runtimeChunk). Here is how it works.

Defaults

By default it now does some optimizations that should work great for most users.

Note: The defaults only affect on-demand chunks, because changing initial chunks would affect the script tags in the HTML. If you can handle this (i. e. when generating the script tags from the entrypoints in stats) you can enable these default optimizations for initial chunks too with optimization.splitChunks.chunks: "all".

webpack automatically splits chunks based on these conditions:

  • New chunk can be shared OR modules are from the node_modules folder
  • New chunk would be bigger than 30kb (before min+gz)
  • Maximum number of parallel request when loading chunks on demand would be lower or equal to 5
  • Maximum number of parallel request at initial page load would be lower or equal to 3

When trying to fullfill the last two conditions, bigger chunks are preferred.

Let's take a look at some examples.

Example 1

// entry.js
import("./a");
// a.js
import "react";
// ...

Result: A separate chunk would be created containing react. At the import call this chunk is loaded in parallel to the original chunk containing ./a.

Why:

  • Condition 1: The chunk contains modules from node_modules
  • Condition 2: react is bigger than 30kb
  • Condition 3: Number of parallel requests at the import call is 2
  • Condition 4: Doesn't affect request at initial page load

Why does this make sense?

react probably doesn't change very often compared to your application code. By moving it into a separate chunk this chunk can be cached separately from your app code (assuming you are using Long Term Caching: chunkhash, records, Cache-Control).

Example 2

// entry.js
import("./a");
import("./b");
// a.js
import "./helpers"; // helpers is 40kb in size
// ...
// b.js
import "./helpers";
import "./more-helpers"; // more-helpers is also 40kb in size
// ...

Result: A separate chunk would be created containing ./helpers and all dependencies of it. At the import calls this chunk is loaded in parallel to the original chunks.

Why:

  • Condition 1: The chunk is shared between both import calls
  • Condition 2: helpers is bigger than 30kb
  • Condition 3: Number of parallel requests at the import calls is 2
  • Condition 4: Doesn't affect request at initial page load

Why does this make sense?

Putting the helpers code into each chunk may means it need to downloaded twice by the user. By using a separate chunk it's only downloaded once. Actually it's a tradeoff, because now we pay the cost of an additional request. That's why there is a minimum size of 30kb.


With optimizations.splitChunks.chunks: "all" the same would happend for initial chunks. Chunks can even be shared between entrypoints and on-demand loading.

Configuration

For these people that like to have more control over this functionality, there are a lot of options to fit it to your needs.

Disclaimer: Don't try to optimize manually without measuring. The defaults are choosen to fit best practices of web performance.

Cache Groups

The optimization assigns modules to cache groups.

The defaults assigns all modules from node_modules to a cache group called vendors and all modules duplicated in at least 2 chunks to a change group default.

A module can be assigned to multiple cache groups. The optimization then prefers the cache group with the higher priority (priority option) or that one that forms bigger chunks.

Conditions

Modules from the same chunks and cache group will form a new chunk when all conditions are fullfilled.

There are 4 options to configure the conditions:

  • minSize (default: 30000) Minimum size for a chunk.
  • minChunks (default: 1) Minimum number of chunks that share a module before splitting
  • maxInitialRequests (default 3) Maximum number of parallel requests at an entrypoint
  • maxAsyncRequests (default 5) Maximum number of parallel requests at on-demand loading

Naming

To control the chunk name of the split chunk the name option can be used.

Note: When assigning equal names to different split chunks they are merged together. This can be used i. e. to put all vendor modules into a single chunk shared by all other entrypoints/splitpoints, but I don't recommend doing so. This can lead to more code downloaded than needed.

The magic value true automatically chooses a name based on chunks and cache group key. Elsewise a string or function can be passed.

When the name matches an entrypoint name, the entrypoint is removed.

Select chunks

With the chunks option the selected chunks can be configured. There are 3 values possible "initial", "async" and "all". When configured the optimization only selects initial chunks, on-demand chunks or all chunks.

The option reuseExistingChunk allows to reuse existing chunks instead of creating a new one when modules match exactly.

This can be controlled per cache group.

Select modules

The test option controls which modules are selected by this cache group. Omitting it selects all modules. It can be a RegExp, string or function.

It can match the absolute module resource path or chunk names. When a chunk name is matched, all modules in this chunk are selected.

Configurate cache groups

This is the default configuration:

splitChunks: {
	chunks: "async",
	minSize: 30000,
	minChunks: 1,
	maxAsyncRequests: 5,
	maxInitialRequests: 3,
	name: true,
	cacheGroups: {
		default: {
			minChunks: 2,
			priority: -20
			reuseExistingChunk: true,
		},
		vendors: {
			test: /[\\/]node_modules[\\/]/,
			priority: -10
		}
	}
}

By default cache groups inherit options from splitChunks.*, but test, priority and reuseExistingChunk can only be configured on cache group level.

cacheGroups is an object where keys are cache group keys and values are options:

Otherwise all options from the options listed above are possible: chunks, minSize, minChunks, maxAsyncRequests, maxInitialRequests, name.

To disable the default groups pass false: optimization.splitChunks.cacheGroups.default: false

The priority of the default groups are negative so any custom cache group takes higher priority (default 0).

Here are some examples and their effect:

splitChunks: {
	cacheGroups: {
		commons: {
			name: "commons",
			chunks: "initial",
			minChunks: 2
		}
	}
}

Create a commons chunk, which includes all code shared between entrypoints.

Note: This downloads more code than neccessary.

splitChunks: {
	cacheGroups: {
		commons: {
			test: /[\\/]node_modules[\\/]
			name: "vendors",
			chunks: "all"
		}
	}
}

Create a vendors chunk, which includes all code from node_modules in the whole application.

Note: This downloads more code than neccessary.

optimization.runtimeChunk

optimization.runtimeChunk: true adds an additonal chunk to each entrypoint containing only the runtime.

@creage
Copy link

creage commented Mar 14, 2018

Could someone please advice what config should I use in Webpack4 to get same results as Webpack3 gave with

new webpack.optimize.CommonsChunkPlugin({
    deepChildren: true,
    async: 'common',
    minChunks: 2
})

As my bundles had no overlaps on V3, and on V4 my overlapping is terrible 1186 files were bundled into 56 bundles. Of those, 34 bundles have overlaps. Tried different options, but can't get the same result.

@TheLarkInn
Copy link

@nirvinm compilation.stats will contain the chunkGraph information including which chunks have parents/children (which determines order)

@christianhg
Copy link

Using webpack 3 and CommonsChunkPlugin I'm making sure none of my entries copy anything from one another. It might be a peculiar use case, but it's what I need right now for this project. I looks something like this:

module.exports = {
  entry: {
    core: './src/core/index.js',
    add: './src/plugins/add/index.js',
    bar: './src/plugins/bar/index.js',
    foo: './src/plugins/foo/index.js',
    subtract: './src/plugins/subtract/index.js'
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      // All chunk names have to be listed here. They are ordered a the way
      // that any chunk dependency needs to be listed after the chunk that
      // depends on it. Chunks with many dependencies are in the beginning of
      // the array and chunks with no dependencies are in the end.
      names: ['bar', 'foo', 'add', 'subtract', 'core']
    })
  ]
}

Is it possible to reach a similar output with webpack 4?

@leuvi
Copy link

leuvi commented Mar 16, 2018

I have the same problem as you @l0gicgate

@dtothefp
Copy link

I'm upgrading from Webpack v2 to Webpack v4. I'm using mini-css-extract-plugin to replace extract-text-webpack-plugin. Previously I was using require.ensure to create multiple JS chunks but CSS modules imported into chunks were creating only a single CSS file. I'd like to maintain this functionality but I cannot seem to create a single CSS chunk. Tried the config below but it's not doing anything 🤷‍♂️

    optimization: {
      splitChunks: {
        cacheGroups: {
          commons: {
            name: 'commons',
            test: /\.css$/,
            chunks: 'all',
            minChunks: 2,
            enforce: true
          }
        }
      }
    },

@mnpenner
Copy link

mnpenner commented Mar 16, 2018

@TheLarkInn Where is this chunkGraph you speak of?

I found assets.compilation.chunkGroups.0.chunks.0.files -- is that guaranteed to be in the proper order for inserting into HTML?

image

Specifically, something like this:

{
    apply: function(compiler) {
        compiler.plugin('done', function(stats, done) {
            let assets = {};
            
            for(let chunkGroup of stats.compilation.chunkGroups) {
                if(chunkGroup.name) {
                    let files = [];
                    for(let chunk of chunkGroup.chunks) {
                        files.push(...chunk.files);
                    }
                    assets[chunkGroup.name] = files;
                }
            }

            fs.writeFile('webpack.stats.json', JSON.stringify({
                assetsByChunkName: assets,
                publicPath: stats.compilation.outputOptions.publicPath
            }), done);
        });
    }
},

Will spit out this JSON:

{
    "assetsByChunkName": {
        "main": [
            "runtime~main.a23dfea309e23d13bfcb.js",
            "runtime~main.a23dfea309e23d13bfcb.js.map",
            "chunk.81da97be08338e4f2807.css",
            "chunk.81da97be08338e4f2807.js",
            "chunk.81da97be08338e4f2807.css.map",
            "chunk.81da97be08338e4f2807.js.map",
            "chunk.d68430785367f8475580.css",
            "chunk.d68430785367f8475580.js",
            "chunk.d68430785367f8475580.css.map",
            "chunk.d68430785367f8475580.js.map"
        ],
        "print": [
            "runtime~print.a22d41d203e00584dadd.js",
            "runtime~print.a22d41d203e00584dadd.js.map",
            "chunk.00ae08b2c535eb95bb2e.css",
            "chunk.00ae08b2c535eb95bb2e.js",
            "chunk.00ae08b2c535eb95bb2e.css.map",
            "chunk.00ae08b2c535eb95bb2e.js.map"
        ]
    },
    "publicPath": "/assets/"
}

Which should be easily parseable in your language of choice.

@jtomaszewski
Copy link

jtomaszewski commented Mar 19, 2018

FYI: Documentation for SplitChunksPlugin which is currently in progress was very helpful to us during migration from webpack 3 to webpack 4.

Here's how we migrated our chunks configuration while keeping the same functionality as we had before:

// BEFORE (webpack 3)
  const config = { 
    entry: {
      app: ['./src/ng2/app.module'],
      main: ['./src/main-admin'],
    },
    plugins: [
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendors',
        minChunks: function(module) {
          return (
            module.resource &&
            (module.resource.startsWith(root('node_modules')) ||
              module.resource.startsWith(root('vendor')))
          );
        },
      }),
      new webpack.optimize.CommonsChunkPlugin({
        name: 'commons',
        chunks: ['app', 'main'],
        minChunks: function(module) {
          return module.resource && module.resource.startsWith(root('src'));
        },
      }),
    ]
  };

// AFTER (webpack 4)
  const config = { 
    entry: {
      main: [
        './src/ng2/app.module',
        './src/main-admin',
      ],
    },
    optimization: {
      splitChunks: {
        chunks: 'all',
        minSize: 0,
        maxAsyncRequests: Infinity,
        maxInitialRequests: Infinity,
        name: true,
        cacheGroups: {
          default: {
            chunks: 'async',
            minSize: 30000,
            minChunks: 2,
            maxAsyncRequests: 5,
            maxInitialRequests: 3,
            priority: -20,
            reuseExistingChunk: true,
          },
          vendors: {
            name: 'vendors',
            enforce: true,
            test: function(module) {
              return (
                module.resource &&
                (module.resource.startsWith(root('node_modules')) ||
                  module.resource.startsWith(root('vendor')))
              );
            },
            priority: -10,
            reuseExistingChunk: true,
          },
          commons: {
            name: 'commons',
            chunks: 'initial',
            minChunks: 2,
            test: function(module) {
              return module.resource && module.resource.startsWith(root('src'));
            },
            priority: -5,
            reuseExistingChunk: true,
          },
        },
      },
    }
  };

@alexcheuk
Copy link

Does anyone know if this is a bug or a Webpack 4 change?

for the option output.chunkFilename the docs says

This option determines the name of non-entry chunk files

In Webpack 4 this works properly as expect. Unless you split the runtimeChunk into a seperate file.

So using this config

let config = {
    output: {
        publicPath: config.production.publicPath,
        filename: '[name].js',
        chunkFilename: '[name].[chunkhash].js'
    },
    optimization: {
        runtimeChunk: false
    }
}

my entries files will follow the naming filename: '[name].js' and lazyloaded chunks will follow chunkFilename: '[name].[chunkhash].js'

but when I use this config (seperate the runtimeChunk):

let config = {
    output: {
        publicPath: config.production.publicPath,
        filename: '[name].js',
        chunkFilename: '[name].[chunkhash].js'
    },
    optimization: {
        runtimeChunk: { name: 'manifest' }
    }
}

all my files names becomes '[name].[chunkhash].js'

Is this an expected behaviour?

@sherlock1982
Copy link

Hi! All this is very interesting but fine tuning is a bit unclear.
What to do if:

  1. I have async chunk and don't want it to be splitted for vendors. Because webpack splits it into two: async~vendor (big) and async (small, approx. 130bytes). And that's overhead.

  2. I have entrypoint chunk and don't want it to be splitted. Because see 1.

  3. I have entrypoint chunk and do want it to be splitted because it's too big.

Well I understand that I can set chunks to all, initial, async but that changes whole application behavior.
Are there any reasons these shoudn't worry me and generating too small or too big chunks is ok?

@malectro
Copy link

@jtomaszewski i think he means you want to call stats.toJson({entrypoints: true})?

@didschai
Copy link

didschai commented Mar 29, 2018

@jtomaszewski Thanks for your example. I adapted parts of it and the files seem to look OK.
However, if I include the entrypoint bundle (which contains the webpackBootstrap runtime code) in my html page, it is not executed and no chunks are loaded.
This is the config which splits the webapp into 2 areas:

        minimize: false,
        splitChunks: {
            chunks: 'all',
            minSize: 0,
            maxAsyncRequests: Infinity,
            maxInitialRequests: Infinity,
            name: true,
            cacheGroups:
                {
                    default: {
                        chunks: 'async',
                        minSize: 30000,
                        minChunks: 2,
                        maxAsyncRequests: 5,
                        maxInitialRequests: 3,
                        priority: -20,
                        reuseExistingChunk: true,
                    },
                    main: {
                        name: "main",
                        test: function (module) {
                            return (
                              module.resource &&
                              (module.resource.includes('node_modules') ||
                                module.resource.includes('Root'))
                            );
                        },
                        reuseExistingChunk: true,
                        priority: -10,
                        enforce: true
                    },
                    admin: {
                        name: "admin",
                        test: function (module) {
                            return (
                              module.resource &&
                              (module.resource.includes('node_modules') ||
                                module.resource.includes('Admin'))
                            );
                        },
                        reuseExistingChunk: true,
                        priority: -9,
                        enforce: true
                    }
                }
        }
    }

the output file structure is:

./Root/...    // some other bundles
./Admin/shared/main.bundle.js
./Admin/dashboard/index.js    // this should be the main entry of admin area
./2.chunk.js
...
./admin.chunk.js
./main.chunk.js

is there anything I'm still missing?
Thanks!

@BalticSoft
Copy link

Hi!. What means enforce: true ?

@BalticSoft
Copy link

BalticSoft commented Mar 30, 2018

I have
new webpack.optimize.CommonsChunkPlugin({ name: "commons", filename: "commons_w.js", minChunks: 3, }),
But when i replaced for
optimization: { splitChunks: { cacheGroups: { common: { name: 'common_w', chunks: 'all', minChunks: 2, enforce: true, },}, } },. I have error "require is not defined".

index.html
`<script src="/assets/js/r/common_w"></script>
....

<script src="[other]"></script>

`
Thanks!

@budarin
Copy link

budarin commented Apr 4, 2018

I can not optimize my bundles with a new version

here is my config:

export default {
    mode: 'production',
    target: 'web',
    cache: true,
    entry: {
        client: './src/client/index.js',
    },
    output: {
        path: path.resolve('./dist'),
        filename: '[name].[hash].js',
        chunkFilename: '[name].[chunkhash].chunk.js',
        publicPath: '/',
    },
    // devtool: 'inline-cheap-module-source-map',
    optimization: {
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /node_modules/, // you may add "vendor.js" here if you want to
                    name: 'vendor',
                    chunks: 'all',
                    enforce: true,
                },
            },
        },
        runtimeChunk: {
            name: 'runtime',
        },
        minimizer: [new BabiliPlugin(), new OptimizeJsPlugin({ sourceMap: false })],
        occurrenceOrder: true,
    },
...

after building many bundles have common modules.
How to lift common modules to to a parent bundle?

Thanks

@jamieYou
Copy link

jamieYou commented Apr 5, 2018

How does webpack4 not generate a common file when processing multiple entries?

My webpack.config file.

entry: {
  client: '',
  admin: '',
},
optimization: {
  splitChunks: {
    chunks: 'all'
  },
},

However, in the case of multiple portals, the code shared by the third-party code and the two portals is split into several files.

    admin.bundle.js  
    admin~client.chunk.js 
    client.bundle.js    
    vendors~admin~client.chunk.js
    vendors~client.chunk.js
    // Occasionally there will be one more document
    // vendors~admin.chunk.js

My expectation is that the files after the two portals are packaged are not dependent on each other.
which is

    admin.bundle.js  
    vendors~admin.chunk.js 
    // ---------------------------
    client.bundle.js    
    vendors~client.chunk.js

@MLuminary
Copy link

hi,I'm just a beginner and i have an unsolvable problem

this is my webpack.config.js

entry:{
    index: './src/js/index.js',
    cart: './src/js/cart.js',
    vendor: ['jquery','./src/js/common.js']
  },
optimization:{
    splitChunks: {
      cacheGroups: {
        commons: {
          name: "vendor",
          chunks: 'initial',
          priority: 10,
          minChunks: 3,
          enforce: true
        }
      }
    },
    runtimeChunk: true
  },

my css file cannot be introduced

when runtimeChunk is false,the css file can be introduced but 0.js and 1.js will appear

Do i have to configure css ? please tell me why , thankshi,I'm just a beginner and i have an unsolvable problem

this is my webpack.config.js

entry:{
    index: './src/js/index.js',
    cart: './src/js/cart.js',
    vendor: ['jquery','./src/js/common.js']
  },
optimization:{
    splitChunks: {
      cacheGroups: {
        commons: {
          name: "vendor",
          chunks: 'initial',
          priority: 10,
          minChunks: 3,
          enforce: true
        }
      }
    },
    runtimeChunk: true
  },

my css file cannot be introduced

when runtimeChunk is false,the css file can be introduced but 0.js and 1.js will appear

Do i have to configure css ? please tell me why , thanks

@aspirisen
Copy link

What is the correct config for webpack 4 if in previous I had this. When i tried I always had all the common and vendor chunks together.
Thanks.

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

module.exports = {

    context: path.join(__dirname, 'src'),

    entry: {
        home: "./Home",
        order: "./Order",
        profile: "./Profile",
        shop: "./Shop",
        vendor: ["lodash", "jquery"]
    },

    output: {
        path: path.join(__dirname, "built"),
        filename: "[name].js"
    },

    resolve: {
        extensions: ['.js']
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: ["common", 'vendor'],
            minChunks: 2,
        })
    ]

}

@lfkwtz
Copy link

lfkwtz commented Apr 16, 2018

@gricard what did you end up changing to no longer be stuck with 0.bundle.min.js?

@crazyfx1
Copy link

crazyfx1 commented Apr 20, 2018

@aspirisen Did you find a solution for this? I have exactly the same webpack 3 configuration with the array as name property and can't figure out the correct configuration for splitChunks.

@rbinsztock
Copy link

splitChunks: {
	chunks: "async",
	minSize: 30000,
	minChunks: 1,
	maxAsyncRequests: 5,
	maxInitialRequests: 3,
	name: true,
	cacheGroups: {
		default: {
			minChunks: 2,
			priority: -20,
			reuseExistingChunk: true,
		},
		vendors: {
			test: /[\\/]node_modules[\\/]/,
			priority: -10
		}
	}
}

missing one ',' after priority: -20

@budarin
Copy link

budarin commented May 4, 2018

Hi!

How move common modules into parent bundle like it was in webpack3?

    entry: {
        client: './src/client/index.js',
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                default: false,
                vendor: {
                    test: /[\\/]node_modules[\\/]/, // you may add "vendor.js" here if you want to
                    name: 'vendor',
                    chunks: 'all',
                    enforce: true,
                },
            },
        },
        runtimeChunk: {
            name: 'runtime',
        },
        occurrenceOrder: true,
    },

I have common code in many bundles, instead of lifting common code upper in bundles tree (not into the only one common chunk - its not right to have all common code to move into common chunk)

@IanVS
Copy link

IanVS commented May 9, 2018

I'm really struggling right now to duplicate the behavior that CommonsChunkPlugin gave for injecting code into all entries, by giving it a name which was the same as an entry point. It seems the behavior now for SplitChunksPlugin is to throw away the entry?! @simonjoom, I'm basically trying to do the same as you, were you able to figure it out?

@arthow4n
Copy link

Here's a side-by-side guide for folks trying to reproduce the "vendor bundle" chunking behavior in Webpack 4, this worked for me.
The key point is that you can pass function into chunks and test (undocumented in the doc of SplitChunksPlugin). After knowing this, all you need is insert a function with debugger statement into it, trial-and-error, look at the output of webpack-bundle-analyzer, and find out what works for you.
I couldn't figure this out without reading the webpack config schema. https://github.com/webpack/webpack/blob/master/schemas/WebpackOptions.json

@budarin might be interested in this?

Good Old Webpack 3

// vendor.js
import moment from 'moment';
moment.locale('zh-tw');
// application.js
console.log('application');
<!-- index.html -->
<script src="vendor.js"></script>
<script src="application.js"></script>
// webpack.config.js
module.exports = {
  entry: {
    vendor: 'src/vendor.js',
    application: 'src/application.js',
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      chunks: ['application'],
      minChunks: (module) => {
        const context = module.context;
        return context && context.indexOf('node_modules') >= 0;
      },
    }),
  ],
};

Upgrading to Webpack 4

The vendor bundle doesn't have to be modified.

// vendor.js
import moment from 'moment';
moment.locale('zh-tw');

You must import the vendor bundle explicitly in Webpack 4 even if you have placed both of the bundle script tags in order on the HTML.

// application.js
import './vendor';
console.log('application');

The HTML doesn't have to be modified.

<!-- index.html -->
<script src="vendor.js"></script>
<script src="application.js"></script>

Update your Webpack config:

// webpack.config.js
module.exports = {
  entry: {
    vendor: 'src/vendor.js',
    application: 'src/application.js',
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          name: 'vendor',
          reuseExistingChunk: true,
          chunks: chunk => ['vendor', 'application'].includes(chunk.name),
          test: module => /[\\/]node_modules[\\/]/.test(module.context),
          minChunks: 1,
          minSize: 0,
        },
      },
    },
  },
};

@petrdanecek
Copy link

Regards the vendor.js without the vendor.css (the node_module related CSS is not extracted to independent vendor.css, but the CSS is kept in the app.css instead of), this would be the solution:

  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/].*(?<!\.(sa|sc|c)ss)$/,
          name: 'vendor',
          chunks: 'all'
        }
      }
    }
  },

Test matches all files in node_modules expect the SCSS|SASS|CSS. Both app and vendor styles are extracted into app.css.

@magicdawn
Copy link

typo
image

@ufo1792
Copy link

ufo1792 commented Jan 8, 2019

i tried many times.. but frustrated..
i'm poor at english.. how can i solve this code? very very thank you
very simple code..
i want to make file name is 'vendor.bundle.js' please help
i know that using optimization, splitchunks because difference of webpack versions but i tried many but i'm poor in this.
anyone please help me.....

plugins:[
new webpack.optimize.CommonsChunkPlugin('vendor','vendor.bundle.js')
i think this code need to be modyfied

default

@vsTianhao
Copy link

vsTianhao commented May 10, 2019

There's a mistake.

无标题

comma error

@hanweiit007
Copy link

hanweiit007 commented Sep 18, 2019

I would like to ask how to modify my configuration.
CommonsChunkPlugin change to splitChunks.

entry: {
	main: ['./app/js/common/vendor.js', './app/js/common/common.js', './app/index.js'],
	ie8: './app/js/polyfills/ie8-polyfill.js',
	ie9: './app/js/polyfills/ie9-polyfill.js'
},
new webpack.optimize.CommonsChunkPlugin({
	name: 'app-common',
	chunks: chunksForAppCommon,
	children: false,
	minChunks: function(module, count) {
	        if (module.context &&
		        module.context.indexOf('node_modules') !== -1 &&
		        module.context.indexOf('i18n-messages') === -1 && count > 0) {
		        console.log("app-common 1: " + count + "\t" + module.resource);
		        return true;
	        }
	        if (!module.resource) {
		        console.log("app-common 2: " + count + "\t" + module.resource + "\t" + module.context);
		        return true;
	        }
	        if (module.context &&
		        module.context.indexOf('i18n-messages') === -1 && count > 0 && count === chunksForAppCommon.length) {
		        console.log("app-common 3: " + count + "\t" + module.resource);
		        return true;
	        }
	        console.log("app-common 9: " + count + "\t" + module.resource);
	        return false;
        }
}),
new webpack.optimize.CommonsChunkPlugin({
	name: 'runtime',
	minChunks: Infinity
}),

@carldiegelmann
Copy link

carldiegelmann commented Dec 19, 2019

How can I write this Chunk configuration with Webpack 4:

config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', // make sure that only the explicitly defined entries are included in the bundle minChunks: Infinity, }) ); config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ name: 'ct-core', chunks: Object.keys(moduleEntries), minChunks: 2, }) );

@tonix-tuft
Copy link

Where can I find a guide and or tutorial explaining all this stuff but more in detail and in a friendlier way? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment