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?

+ webpack@4.0.0-beta.2
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
...
+ webpack-cli@2.0.6
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
...
+ uglifyjs-webpack-plugin@1.2.0
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

> mmcbuild@2.0.0 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"'
        })
    ]

};
@mariuslazar93
Copy link

mariuslazar93 commented Mar 21, 2018

Thanks for the post. I've been through something similar. I've also tried to set up SASS compilation to CSS plus autoprefixer and had some issues with while developing. Seems like because of the mini-css-extract-plugin, the webpack-dev-server doesn't detect changes to your SCSS files. The workaround was to add the style-loader for development. The working solution for me:

{
        test: /\.scss$/,
        use: [
          (isLocal ? 'style-loader' : MiniCssExtractPlugin.loader),
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2,
              minimize: !isLocal,
              sourceMap: isLocal,
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              ident: 'postcss',
              plugins: () => [precss(), autoprefixer()],
            },
          },
          'sass-loader',
        ],
      },

See this issue on mini-css-extract-plugin for updates.

@shivkoirala
Copy link

shivkoirala commented Mar 27, 2018

Such huge changes , with out any document , repent putting all my build using webpack all prod builds failing.

@idessignflo
Copy link

hey
i have the same problem with webpack@4.3.0
when i run webpack i have the following error

C:\Idessign>webpack
Hash: 18bc2fd105d4883da519
Version: webpack 4.3.0
Time: 114ms
Built at: 2018-3-28 13:44:12

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 Entry module not found: Error: Can't resolve './src' in 'C:\Idessign'

look my webpack.config.js

const webpack = require('webpack'),
path = require('path'),
ExtractTextPlugin = require("extract-text-webpack-plugin"),
nodeExternals = require('webpack-node-externals'),
srcPath = path.resolve(__dirname, "./src/"),
distPath = path.resolve(__dirname, './src/build/');
const HTMLPlugin = require('html-webpack-plugin');

const BUILD_DIR = path.resolve(__dirname , "./src/build/");
const APP_DIR = path.resolve(__dirname, "./src/");
const IMG_DIR = path.resolve(__dirname, './public/images');

const browserConfig = {
entry :
APP_DIR + 'client/index.js',

  output : {
  path : BUILD_DIR,
  filename : "[name] bundle.js",
  publicPath:BUILD_DIR,
},

module : {
    rules : [
        {
            test : /\.(js|jsx)$/,
            include : APP_DIR,
            loader : 'babel-loader',
            exclude: /node_modules/,
            query : {
            presets:[ 'react', 'es2015'],
          }
       ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
       new HTMLPlugin(),
  ]

};
help please

@LiranBri
Copy link

LiranBri commented Apr 2, 2018

+999999999

@gricard
Copy link
Author

gricard commented Apr 2, 2018

@idessignflo it says

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

Add in mode: 'production' or mode: 'development' in your config's top level. Look at mine in the gist as an example.

@gregdeane
Copy link

Very helpful. Thanks!!

@mkastner
Copy link

mkastner commented Apr 5, 2018

You just saved me lots of otherwise wasted hours and propably even days.

@allancarait
Copy link

Thanks! Really helpful!

@givingwu
Copy link

givingwu commented Apr 8, 2018

I don't know what helps me, but it's all right things.

@gricard
Copy link
Author

gricard commented Apr 9, 2018

For those using Jest for testing, I found that I had to follow the advice on https://github.com/mwolson/jest-webpack-alias and convert to using https://github.com/tleunen/babel-plugin-module-resolver to resolve my webpack aliases. I ended up making a separate list of them in my .babelrc as mentioned in the Getting Started section of their README.

@doberkofler
Copy link

very amusing ;-)

@mrchief
Copy link

mrchief commented Apr 18, 2018

This rant is very similar to the experience I'm having. Thanks for the laughs.

Using webpack 4 resulted in larger bundles (in production mode) so I don't know where the magic isn't happening. Lack of docs and the fact the 3.0 docs are being masqueraded as 4.0 docs just add to the confusion. Half (or maybe more) of the ecosystem (plugins, loaders) is yet to catch up. Plus webpack 5 may make some of them obsolete leaving very less incentive for the authors to even spend the time to upgrade them.

The more I read into webpack 4, the more it feels like the Windows Vista release of webpacks. I'll just wait for the Windows 7 release I guess. :)

@nobleach
Copy link

I found my larger bundles were due to running webpack in prod mode, but forgetting to explicitly set NODE_ENV=production which used my dev mode from my .babelrc.

@mrchief
Copy link

mrchief commented Apr 27, 2018

@nobleach I'm doing that and I still get non-minified bundles. I wonder if it has anything to do with mode flag.

@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