Webpack is a module bundler that takes all your assets and turns them into easily distributable packages. Once you understand it, it can drastically simplify your workflow, but getting started with it can be painful.
What I found difficult in starting to use it, was that I didn’t have a good model of what was going on. It seemed like magic. This made it hard to fix errors when they occurred and scared me away from trying to tailor the configurations I was using.
So I wrote myself an idiots guide to configuring Webpack. It helped me, maybe it can help you.
Webpack bundles modules for web applications. Pretty much anything can be treated as a module. Images, CSS, JS, HTML, preprocessor files (.pug / .styl / .sass etc)… anything. It takes in all your modules (or files), figures out their dependencies and outputs some nice static assets, structured the way you want.
The modules we need to
npm install for this are:
| Source files
| Desired output
| Example contents of JS files
--config option. There are four key parts of this configuration file that will get your Webpack build going.
The starting point of your application. This option tells Webpack where to start. It will follow dependencies it finds in this file. It will then do the same for each dependency it finds.
The output option tells Webpack how to output your bundled assets.
Loaders only run transforms on a per-file basis, once you have compiled your files into a bundle you can use plugins to further customise and perform actions on your outputted bundle.
To use a plugin, you require() it and add it to the plugins array. Most plugins have options that can be customised when they are used. You initiate the plugin by calling it with
new. This is because you can use the same plugin multiple times with different configurations.
If you have named your config with the default name, like in the above example you only need to run
webpack from the command line in the same directory as your Webpack config. If you named it something else, say ‘config.js’, you can pass the configuration file to Webpack on the CLI like so:
webpack --config config.js
Thats it. Webpack will process the files and output the finished product into the directory structure you want, ready to deploy to a webserver.
There’s a plethora of options that are not going to be in this. Not because they aren’t useful but because they can be safely ignored in the interest of understanding. Once you have wrapped your brain around the general model of whats occurring, I find the rest is all fairly simple.