Skip to content

Instantly share code, notes, and snippets.

@gricard
Last active February 29, 2024 20:23
Show Gist options
  • Save gricard/e8057f7de1029f9036a990af95c62ba8 to your computer and use it in GitHub Desktop.
Save gricard/e8057f7de1029f9036a990af95c62ba8 to your computer and use it in GitHub Desktop.
Just some notes about my attempt to upgrade to webpack 4

If you enjoyed reading this, I'm intending to do more blogging like this over here: https://cdgd.tech

This is not a complaint about Webpack or v4 in any way. This is just a record of my process trying it out so I could provide feedback to the webpack team

Hmm... I don't see any docs for 4.0 on https://webpack.js.org. I guess I'll just wing it. All I need to do is npm i -D webpack@next, right?

+ [email protected]
added 1 package, removed 20 packages and updated 4 packages in 13.081s

Cool! Ok...

$ npm run buildjs

The CLI moved into a separate package: webpack-cli.
Please install 'webpack-cli' in addition to webpack itself to use the CLI.
-> When using npm: npm install webpack-cli -D
-> When using yarn: yarn add webpack-cli -D

Agh! Alright. I'll install that too.

$ npm i -D webpack-cli@next
npm ERR! code ETARGET
npm ERR! notarget No matching version found for webpack-cli@next
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

Oh, maybe it doesn't need '@next'?

$ npm i -D webpack-cli
...
+ [email protected]
added 209 packages in 39.639s

Ok. Let's try that build again...

Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead.

Alrighty, it's supposed to be "zero config" now. Let's see what happens when I just take that out. #0CJS #yolo

edits webpack config

But wait, how do I specify the name for my vendor bundle? Well, let's try running it and see what happens.

$ npm run buildjs
...
Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.

Oh, that too, eh? Ok.

I'll cut these out, then:

new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    filename: 'vendor.min.js',
    minChunks: module => /node_modules/.test(module.resource)
}),

new webpack.optimize.UglifyJsPlugin({
    compress: {
	unused: false
    }
}),

Ok, now...

$ npm run buildjs
...
Error: Cannot find module 'uglifyjs-webpack-plugin'

Gah.

$ npm i -D uglifyjs-webpack-plugin
...
+ [email protected]
added 1 package, removed 1 package and updated 5 packages in 10.899s

Let's try again...

$ npm run buildjs

...

 10% building modules 1/1 modules 0 active(node:13692) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
(node:13692) DeprecationWarning: Tapable.apply is deprecated. Call apply on the plugin directly instead         Hash: 36f7a2376b4b763b21f0                Version: webpack 4.0.0-beta.2
Time: 8262ms
Built at: 2018-2-22 07:58:12
 1 asset
Entrypoint app =
Entrypoint vendor = player.min.js

...module list...

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.

ERROR in chunk app [entry]
player.min.js
Conflict: Multiple assets emit to the same filename player.min.js
webpack-cli 2.0.6
Usage: https://webpack.js.org/api/cli/
Usage without config file: webpack <entry> [<entry>] --output [-o] <output>
Usage with config file: webpack
...entire webpack --help output...

wat.

googles

reads webpack beta article

Ok. I guess I don't need to pass --optimize-minimize anymore. And I need this mode config now. Ok. Oh, and it did say to install webpack-cli first. Duh. Should have googled and read this first.

 DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
(node:3244) DeprecationWarning: Tapable.apply is deprecated. Call apply on the plugin directly instead

Where the hell is this even coming from? I have never seen this before. Whatever...

Why am I getting the webpack help output? Let's get rid of everything but the --config option and see what happens.

$ npm run buildjs

> [email protected] buildjs C:\Users\gabric\PhpstormProjects\MMC-TRUNK\player
> cross-env BABEL_ENV=production webpack --config build/webpack.prod.config.js

(node:11724) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
Hash: e0ad5ef31f134fbe2892
Version: webpack 4.0.0-beta.2
Time: 7359ms
Built at: 2018-2-22 08:08:08
 1 asset
Entrypoint app =
Entrypoint vendor = player.min.js
...modules...
    + 473 hidden modules

ERROR in chunk app [entry]
player.min.js
Conflict: Multiple assets emit to the same filename player.min.js
webpack-cli 2.0.6
Usage: https://webpack.js.org/api/cli/
Usage without config file: webpack <entry> [<entry>] --output [-o] <output>
Usage with config file: webpack
...entire help output again...

Right. That didn't help.

Let's just try to add the new config for the CommonsChunkPlugin replacement and see what happens.

I'll use this as a guide, I guess.

reads

Ok, so I just add this to my config, I guess:

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

Nope. That's got a syntax error.

fixes

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

Sweet big-ass red error, Batman!

$ npm run buildjs

> cross-env BABEL_ENV=production webpack --display-modules --progress --colors --config build/webpack.prod.config.js

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration has an unknown property 'splitChunks'. These properties are valid:
   object { mode?, amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, externals?, loader?, module?, name?, node?, output?, optimization?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
   For typos: please correct them.
   For loader options: webpack 2 no longer allows custom properties in configuration.
     Loaders should be updated to allow passing options via loader options in module.rules.
     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
     plugins: [
       new webpack.LoaderOptionsPlugin({
         // test: /\.xxx$/, // may apply this only for some modules
         options: {
           splitChunks: ...
         }
       })
     ]

What do you mean splitChunks is unknown?

googles

Nothing helpful...

checks webpack beta article again

Ok, so that says optimization.splitChunks, let's try this, then:

(Edit: oh, duh, it actually says config.optimization.splitChunks in the warning about CommonsChunkPlugin... Durrrr)

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

Why am I still getting this webpack help output? How the heck do I fix this error?

ERROR in chunk app [entry]
player.min.js
Conflict: Multiple assets emit to the same filename player.min.js

Where are the docs for the config options for 4.0?

Maybe I'll just check the source... There's a potentially relevant example in there, but it's not really clear if it does what I need to do, as it's not really documented.

Hmm.. Actually, this example makes a little more sense. Looks like I need to change output.filename to use '[name]' instead of the explicit name I had before.

$ npm run buildjs

> cross-env BABEL_ENV=production webpack --display-modules --progress --colors --config build/webpack.prod.config.js

 10% building modules 1/1 modules 0 active(node:7716) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
(node:7716) DeprecationWarning: Tapable.apply is deprecated. Call apply on the plugin directly instead          Hash: 73c0f51bb0e7ea4f011a                Version: webpack 4.0.0-beta.2
Time: 15589ms
Built at: 2018-2-22 08:38:10
        Asset     Size  Chunks                    Chunk Names
vendor.min.js  474 KiB       0  [emitted]  [big]  vendor
   app.min.js  502 KiB       1  [emitted]  [big]  app
Entrypoint app [big] = vendor.min.js app.min.js
...shitload of modules...

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  vendor.min.js (474 KiB)
  app.min.js (502 KiB)

WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  app (975 KiB)
      vendor.min.js
      app.min.js


WARNING in webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/

Oh, shit. Did that actually work? Yes!

Wait, but now I have app.min.js and vendor.min.js. Oh, I see. I need to rename my entry to have that used as the filename.

edits config

Hash: 9f00b0adf58d23d3596a                Version: webpack 4.0.0-beta.2
Time: 12777ms
Built at: 2018-2-22 08:41:44
        Asset     Size  Chunks                    Chunk Names
vendor.min.js  474 KiB       0  [emitted]  [big]  vendor
player.min.js  502 KiB       1  [emitted]  [big]  player
Entrypoint player [big] = vendor.min.js player.min.js

There we go!

Oh, wait, is it doing the minimization? Yeah, must be. This article says it's on by default in production mode now. Ok, cool.

Webpack 3.11 build

$ time npm run buildjs

> cross-env BABEL_ENV=production webpack --optimize-minimize --display-modules --progress --colors --config build/webpack.prod.config.js

Hash: e7e52a3df71a5bc44924
Version: webpack 3.11.0
Time: 19783ms
        Asset    Size  Chunks                    Chunk Names
player.min.js  495 kB       0  [emitted]  [big]  app
vendor.min.js  491 kB       1  [emitted]  [big]  vendor
...modules...

real    0m23.698s
user    0m0.046s
sys     0m0.477s

Output file sizes:

player.min.js	491274
vendor.min.js	491988

total		983262

Webpack 4.0.0.beta.2 build

$ time npm run buildjs

> cross-env BABEL_ENV=production webpack --display-modules --progress --colors --config build/webpack.prod.config.js

 10% building modules 1/1 modules 0 active(node:13084) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
(node:13084) DeprecationWarning: Tapable.apply is deprecated. Call apply on the plugin directly instead         Hash: 9f00b0adf58d23d3596a                Version: webpack 4.0.0-beta.2
Time: 8430ms
Built at: 2018-2-22 08:52:15
        Asset     Size  Chunks                    Chunk Names
vendor.min.js  474 KiB       0  [emitted]  [big]  vendor
player.min.js  502 KiB       1  [emitted]  [big]  player
Entrypoint player [big] = vendor.min.js player.min.js

real    0m12.717s
user    0m0.137s
sys     0m0.325s

Output file sizes:

player.min.js	513680
vendor.min.js	484936

total		998616

Summary

Took a while to figure out how to update my config properly, but it works.

57% faster build, 1.5% larger total bundle size (weird, but not a deal-breaker).

Final config

var webpack = require('webpack');

// use resolve() to normalize paths between unix/windows environments
var path = require('path');

function resolve (dir) {
    return path.join(__dirname, '..', dir)
}

module.exports = {

    mode: 'production',

    entry: {
        player: resolve('app/main/index.js'),

        // code splitting: we take all of our vendor code and put it in a separate bundle (vendor.min.js)
        // this way it will have better caching/cache hits since it changes infrequently
        vendor: [
            // local packages
            'clipboard',
            'jquerynotify'

            // npm packages are added to vendor code separately in splitChunks config below
        ]
    },

    output: {
        path: resolve('app/'),
        filename: '[name].min.js'
    },

    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendor',
                    chunks: 'all'
                }
            }
        }
    },

    module: {
        rules: [
            {
                test: /\.css$/,
                loader: 'style!css'
            },
            {
                test: /\.html$/,
                use: 'raw-loader'
            },
            {
                test: /^(?!.*\.{test,min}\.js$).*\.js$/,
                exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader'
                }
            }
        ]
    },

    resolve: {
        modules: [
            resolve('app'),
            resolve('app/css'),
            'node_modules'
        ],

        alias: {
            // external libraries
            jquerynotify: resolve('app/js/jquery.notify.min'),
            clipboard: resolve('app/js/clipboard.min'),

            // directory alias to shorten template paths
            templates: resolve('app/templates')
        }
    },

    plugins: [
        // ensure that we get a production build of any dependencies
        // this is primarily for React, where this removes 179KB from the bundle
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': '"production"'
        })
    ]

};
@jozefcipa
Copy link

Man, you are genius ! ❤️

@quodos
Copy link

quodos commented May 9, 2018

Thanks man ❤️ this made the transition nearly a breeze!

@eliseumds
Copy link

Nice, thank you very much!

@deepfriedbrain
Copy link

deepfriedbrain commented May 20, 2018

I jumped from Webpack 1x straight to 4x and my bundles are now larger by about 4% (which is quite significant). I'm not sure if I'm missing something.

UPDATE: I figured out that the increase was due to inclusion of CSS and JS comments. After excluding those, the bundle size was about 7KB smaller.

@jandresampaio
Copy link

jandresampaio commented May 25, 2018

Great post, with same results.
I guess they talk that crap about smaller bundles when they have a sample app with 2 components.
What about real apps ? Just don't understand...
Everything above 400kb is big ??? Wtf ? Is this a college app build tool ?

@ideaspring-cp
Copy link

So as a newbie to Webpack (and to these types of build tools for JS), I thought I'd start "simple" by following along with countless tutorials available online. Little did I know that starting with Webpack 4 was going to ruin my entire day. At first I was "excited" because one usually learns by overcoming challenges, not just typing-along with tutorials. But man this is crazy-making!

Everything was humming along until getting to CSS/SCSS transforms. I can't seem to find a clear answer (and nothing I'm doing seems to work) for this. Issues like the docs stating "extract-text-plugin" should be replaced with "mini-css-extract-plugin" ... neither of which worked regardless of how many different configs I found online, and tweaks I tried to make. But if you're new to Webpack, there's no way to even guess and what to try since there's nothing to fall back on.

Is it better to change the dependencies to use Webpack 3 and wait-it-out? Or is it better to just use different build tools (e.g., Grunt, Gulp, etc.) Or use other build-tools in addition to Webpack (e.g., do Sass transforms first with another tool, then use Webpack to just deal with JS aspects)?

@tomm1996
Copy link

@ideaspring-cp better use anything but webpack for compiling Sass until the CssWebpackPlugin is finished. The current workflow is kind of awkward and the compile times are unconscionable once you have more than 4000 lines of Sass.

@gauravgrover95
Copy link

awesome post. :) Thanks for writing this.

@lsycxyj
Copy link

lsycxyj commented Jul 31, 2018

Did any one solve the larger size problem? I found that codes bundled by webpack 4 contains some declarations about Symbol while code bundled by webpack 3 doesn't.

@thargenediad
Copy link

Thank you so much for this!

@codyromano
Copy link

Thanks for the thorough write-up! Extremely helpful

@gricard
Copy link
Author

gricard commented Sep 11, 2018

If you enjoyed this, I’m going to continue doing more write-ups like this here: https://cdgd.tech

@v-stickykeys
Copy link

👍

@skylight-ity
Copy link

Best answer :) made me laugh, thank you!

@y0n3r
Copy link

y0n3r commented Jan 15, 2019

I've been updating webpack v3 to v4 under a lot of stress, and this writeup made me crack up. I needed the laugh.
(and a bit of it is helpful for my case, too!)

@dancrew32
Copy link

dancrew32 commented Feb 14, 2019

This should be the first google result for webpack v3 to v4. Thank you so much!

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