migrationwebpack-3commonschunkpluginwebpack-4

Webpack migration 3 -> 4: Error: Cannot find module 'webpack/lib/optimize/CommonsChunkPlugin'


I'm trying to migrate from webpack 3 to webpack 4.

The issue I have is with CommonsChunkPlugin, when I try to run webpack (npm run webpack-dev-server -- --config config/webpack.dev.js), I have the following error:

module.js:529
    throw err;
    ^

Error: Cannot find module 'webpack/lib/optimize/CommonsChunkPlugin'
    at Function.Module._resolveFilename (module.js:527:15)
    at Function.Module._load (module.js:476:23)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/antoinepissot/DEV/Reports/config/webpack.common.js:17:28)
    at Module._compile (module.js:624:30)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)

What is causing this issue ?

I looked at the change log on webpack github and found that CommonsChunkPlugin has been removed

But when I look at the webpack documentation, I can find CommonsChunkPlugin for version 4.1.1

My gut feeling is telling me that CommonsChunkPlugin is deprecated and we should use optimization.splitChunks.

Did anyone experienced the issue and found a good tutorial to migrate from version 3 to 4 ?


Solution

  • As Vardius pointed out in his comment, CommonsChunkPlugin was removed.

    In webpack 4, this behaviour is done using "optimization" field at the root of webpack config.

    For instance, this is how my webpack.config.js looks like now:

    module.exports = function () {
       return {
        resolve: ...
        module: ...
        plugins: ...
        optimization: {
    
           namedModules: true, // old NamedModulesPlugin()
           splitChunks: {      // old CommonsChunkPlugin
              chunks: "all"
           },
           runtimeChunk: true,
           concatenateModules: true // old ModuleConcatenationPlugin
        }
    }