Lesson Weekend

Bundling our code is one way to make it faster; the more files we have to download, the longer it takes to load a site. However, large files will also slow down our site considerably, too. Our users want to access our site as quickly as possible - nobody likes waiting for a page to load, and some users might end up leaving our site altogether if it's too slow. Our goal is to drive traffic to our site, not away from it!

Minifying (or "Uglifying") Code

Our next step is to minify, or uglify, our code. Uglification is the process of taking human-readable code and reducing it to the bare minimum needed for a machine to read it. After all, a machine doesn't care about spacing or concise variable names. Changing a variable name from pingPongCounter to a single letter variable will make our file a little bit smaller. If these kinds of changes are made across the entire file, the file becomes considerably smaller - and faster to download.

Take a look at bundle.js in the dist folder. Webpack has added a lot of code to bundle it and make it more efficient; you can also find our src code tucked away in there and it's still recognizable. The bundle is currently 54 KB; that may not seem big, but once again, in larger applications with many files, the extra size can quickly add up. And honestly, if you're on your phone looking at the site and the network is slow, 54 KB could be pretty slow, too.

Let's "uglify" our code now. First, we'll install the UglifyJS Webpack Plugin:

$ npm install [email protected] --save-dev

Next, we need to make the plugin available to our application:

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');  // new line

module.exports = {
  plugins: [
    new UglifyJsPlugin(),    // new line
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Ping Pong',
      template: './src/index.html',
      inject: 'body'

We used the same process as we did for installing our other plugins:

  • We used npm to load it into our package.json

  • We then require the plugin at the top of webpack.config.js

  • Next we add it to the list of plugins in the module.exports section of webpack.config.js.

That's it. Let's run $ npm run build again and see what happens. Look at bundle.js in the dist folder and you'll see it's been reduced to a single line of uglified, unreadable code! And if you check the size of the file, it's now only 7 KB... about eight times smaller than it was before. The file will now download much more quickly. This is potentially a huge difference in download times for our users!

We can also further minify our HTML; check out HTMLMinifier for more. The documentation says that by default, the css-loader minifies our css. In fact, any assets can be further minified (which is especially useful for larger assets such as images and so on). We only cover minifying JavaScript here, but feel free to explore further on your own!