Skip to content
 

SurviveJS – Webpack 5

Webpack is a module bundler meant for building JavaScript applications and sites. In this book, I will go through main features of webpack while teaching you to compose configuration using webpack-merge.

Incidentally, I developed webpack-merge for the purposes of this book and since then it has become a popular solution for taming the complexity of webpack configuration. The book is meant to web developers ranging from beginners to advanced although you should be familiar with the basic ideas behind JavaScript language to get most out of it.

The book content was developed during many years with the help of the community and it complements the official documentation. Even if you know webpack well already, I have taken care to include short summaries capturing the main points of the book so you can fill the gaps in your knowledge and understanding of the tool.

Testimonials

Clément ParisFront-end Engineer

After weeks failing at configuring webpack, I stumbled upon SurviveJS book while looking for yet another tutorial. Since that day, it has been my go-to resource for every single webpack question I ever had.

Andrea ChiumentiCEORed Software Systems

Brilliant! A must have if you want to to learn webpack but also if need an updated reference guide. I always use it as a reference guide when I develop.

Gavin DoughtieSenior Software EngineerGoogle

Before I worked through the SurviveJS webpack book, my own webpack config, cobbled together from random code on the Internet, was a mystery to me. Afterwards, I have route-splitting and parallel-loading superpowers.

Neeraj SinghFounderBig Binary

Webpack is powerful but configuring it can be painful. Same goes with React. There are so many ways of configuring React with asset compilation, minification etc that it is easy to get lost. This book provides practical tips on how to proceed.

Aaron HarrisSoftware Engineer

This guide was a great starter in taming the Wild West of ESNext-era JavaScript development. Its beauty comes from its commitment to not skipping the fundamentals in favor of a fast demo, but making sure you’re understanding what you’re doing as you bootstrap your next JavaScript-based UI project.

Julien CastelainSoftware EngineerLiferay

This guide is a great way to get started with webpack or improve your existing skills. After a detailed introduction, you’ll start working on a webpack project that provides all you need to push your app to production. Highly recommended.

Availability

Although you can read the book online for free, you can also purchase it in a copy to support the development of the content. See also consulting for other available options.

Table of contents

  1. Foreword It's a funny story how I started with webpack. Before getting addicted to JavaScript, I also developed in Java. I tried GWT (Google Web Toolkit) in that time. GWT is a Java-to-JavaScript Compiler, which has a great feature: code splitting. I liked this feature and missed it in existing JavaScript t…
  2. Preface The book you are reading right now goes years back. It all started with a comment I made on Christian Alfoni's blog in 2014. It was when I discovered webpack and React, and I felt there was a need for a cookbook about the topics. The work began with a GitHub wiki in early 2015. After a while, I re…
  3. Introduction Webpack simplifies web development by solving a fundamental problem: bundling. It takes in various assets, such as JavaScript, CSS, and HTML, and transforms them into a format that's convenient to consume through a browser. Doing this well takes a significant amount of pain away from web developmen…
  4. What is Webpack Webpack is a module bundler. Webpack can take care of bundling alongside a separate task runner. However, the line between bundler and task runner has become blurred thanks to community-developed webpack plugins. Sometimes these plugins are used to perform tasks that are usually done outside of web…
  5. Developing In this part, you get up and running with webpack. You will learn to configure webpack-plugin-serve. Finally, you compose the configuration so that it's possible to expand in the following parts of the book. …
  6. Getting Started Before getting started, make sure you are using a recent version of Node. You should use at least the most current LTS (long-term support) version as the configuration of the book has been written with modern Node features in mind. You should have node and npm (or yarn) commands available at your …
  7. Development Server When developing a frontend without any special tooling, you often end up having to refresh the browser to see changes. Given this gets annoying fast, there's tooling to remedy the problem. The first tools on the market were LiveReload and Browsersync. The point of either is to allow refreshing the…
  8. Composing Configuration Even though not a lot has been done with webpack yet, the amount of configuration is starting to feel substantial. Now you have to be careful about the way you compose it as you have separate production and development targets in the project. The situation can only get worse as you want to add more…
  9. Styling In this part, you will learn about styling-related concerns in detail including loading styles, separating CSS, eliminating unused CSS, and autoprefixing. …
  10. Loading Styles Webpack doesn't handle styling out of the box, and you will have to use loaders and plugins to allow loading style files. In this chapter, you will set up CSS with the project and see how it works out with automatic browser refreshing. When you make a change to the CSS webpack doesn't have to force…
  11. Separating CSS Even though there is a nice build set up now, where did all the CSS go? As per configuration, it has been inlined to JavaScript! Although this can be convenient during development, it doesn't sound ideal. The current solution doesn't allow caching CSS. You can also get a Flash of Unstyled Content …
  12. Eliminating Unused CSS Frameworks like Bootstrap or Tailwind tend to come with a lot of CSS. Often you use only a small part of it and if you aren't careful, you will bundle the unused CSS. PurgeCSS is a tool that can achieve this by analyzing files. It walks through your code and figures out which CSS classes are being…
  13. Autoprefixing It can be challenging to remember which vendor prefixes you have to use for specific CSS rules to support a large variety of users. Autoprefixing solves this problem. It can be enabled through PostCSS and the autoprefixer plugin. autoprefixer uses Can I Use service to figure out which rules should …
  14. Loading Assets In this part, you will learn how to load different types of assets using webpack's loaders. Especially images, fonts, and JavaScript receive particular attention. You also learn how webpack's loader definitions work. …
  15. Loader Definitions Webpack provides multiple ways to set up module loaders. Each loader is a function accepting input and returning output. They can have side effects as they can emit to the file system and can intercept execution to implement caching. Anatomy of a loader Webpack supports common JavaScript formats …
  16. Loading Images Image loading and processing can be a concern when developing sites and applications. The problem can be solved by pushing the images to a separate service that then takes care of optimizing them and provides an interface for consuming them. For smaller scale usage, webpack is a good option as it …
  17. Loading Fonts Loading fonts is similar to loading images. It does come with unique challenges, though. How to know what font formats to support? There can be up to four font formats to worry about if you want to provide first class support to each browser. The problem can be solved by deciding a set of browsers…
  18. Loading JavaScript Webpack processes ES2015 module definitions by default and transforms them into code. It does not transform specific syntax, such as const, though. The resulting code can be problematic especially in the older browsers. To get a better idea of the default transform, we can generate a build while s…
  19. Building In this part, you enable source maps on the build, discuss how to split it into separate bundles in various ways, and learn to tidy up the result. …
  20. Source Maps Source maps in Chrome When your source code has gone through transformations, debugging in the browser becomes a problem. Source maps solve this problem by providing a mapping between the original and the transformed source code. In addition to source compiling to JavaScript, this works for stylin…
  21. Code Splitting Web applications tend to grow big as features are developed. The longer it takes for your site to load, the more frustrating it's to the user. This problem is amplified in a mobile environment where the connections can be slow. Even though splitting bundles can help a notch, they are not the only …
  22. Bundle Splitting Although code splitting gives control over when code is loaded, it's not the only way webpack lets you shape the output. Bundle splitting is a complementary technique that lets you define splitting behavior on the level of configuration. A common use case is extracting so called vendor bundle that…
  23. Tidying Up The current setup doesn't clean the build directory between builds. As a result, it keeps on accumulating files as the project changes. Given this can get annoying, you should clean it up in between. Another nice touch would be to include information about the build itself to the generated bundles…
  24. Optimizing In this part, you will learn about code minification, setting environment variables, adding hashing to filenames, webpack runtime, analyzing build statistics, and improving webpack performance. …
  25. Minifying Since webpack 4, the production output gets minified using terser by default. Terser is an ES2015+ compatible JavaScript-minifier. Compared to UglifyJS, the earlier standard for many projects, it's a future-oriented option. Although webpack minifies the output by default, it's good to understand h…
  26. Tree Shaking Tree shaking is a feature enabled by the ES2015 module definition. The idea is that given it's possible to analyze the module definition statically without running it, webpack can tell which parts of the code are being used and which are not. It's possible to verify this behavior by expanding the a…
  27. Environment Variables Sometimes a part of your code should execute only during development. Or you could have experimental features in your build that are not ready for production yet. Controlling environment variables becomes valuable as you can toggle functionality using them. Since JavaScript minifiers can remove de…
  28. Adding Hashes to Filenames Even though the generated build works, the file names it uses is problematic. It doesn't allow to leverage client level cache efficiently as there's no way tell whether or not a file has changed. Cache invalidation can be achieved by including a hash to the filenames. T> Starting from version 5, w…
  29. Separating a Runtime When webpack writes bundles, it maintains a runtime as well. The runtime includes a manifest of the files to be loaded initially. If the names of the files change, then the manifest changes and the change invalidates the file in which it is contained. For this reason, it can be a good idea to write…
  30. Build Analysis Analyzing build statistics is a good step towards understanding webpack better. The available tooling helps to answer the following questions: What's the composition of the project bundles? What kind of dependencies do project modules have? How does the size of the project change over time? Which …
  31. Performance Webpack's performance out of the box is often enough for small projects. That said, it begins to hit limits as your project grows in scale, and it's a frequent topic in webpack's issue tracker. There are a couple of ground rules when it comes to optimization: Know what to optimize. Perform fast t…
  32. Output This part covers different output techniques webpack provides. You see how to manage a multi-page setup, how to implement server-side rendering, and how to use module federation to develop micro frontends. …
  33. Build Targets Even though webpack is used most commonly for bundling web applications, it can do more. You can use it to target Node or desktop environments, such as Electron. Webpack can also bundle as a library while writing an appropriate output wrapper making it possible to consume the library. Webpack's ou…
  34. Multiple Pages Even though webpack is often used for bundling single-page applications, it's possible to use it with multiple separate pages as well. The idea is similar to the way you generated many output files in the Targets chapter. That's achievable through MiniHtmlWebpackPlugin and a bit of configuration. …
  35. Server-Side Rendering Server-Side Rendering (SSR) is a technique that allows you to serve an initial payload with HTML, JavaScript, CSS, and even application state. You serve a fully rendered HTML page that would make sense even without JavaScript enabled. In addition to providing potential performance benefits, this ca…
  36. Module Federation Micro frontends take the idea of microservices to frontend development. Instead of developing the application or a site as a monolith, the point is to split it as smaller portions programmed separately that are then tied together during runtime. With the approach, you can use different technologie…
  37. Techniques In this part, you will learn to use webpack techniques such as dynamic loading, using web workers, internationalization, testing, deploying, and package consumption. …
  38. Dynamic Loading Even though you can get far with webpack's code splitting features covered in the Code Splitting chapter, there's more to it. Webpack provides more dynamic ways to deal with code through require.context. Dynamic loading with require.context require.context provides a general form of code splittin…
  39. Web Workers Web workers allow you to push work outside of main execution thread of JavaScript, making them convenient for lengthy computations and background work. Moving data between the main thread and the worker comes with communication-related overhead. The split provides isolation that forces workers to …
  40. Internationalization Internationalization (i18n) is a big topic by itself. The broadest definition has to do with translating your user interface to other languages. Localization (l10n) is a more specific term, and it describes how to adapt your application to a particular locale or market. Different locales can have t…
  41. Testing Testing is a vital part of development. Even though techniques, such as linting, can help to spot and solve issues, they have their limitations. Testing can be applied to the code and an application on many different levels. You can unit test a specific piece of code, or you can look at the applic…
  42. Deploying Applications A project built with webpack can be deployed to a variety of environments. A public project that doesn't rely on a backend can be pushed to GitHub Pages using the gh-pages package. Also, there are a variety of webpack plugins that can target other environments, such as S3. Deploying with gh-pages …
  43. Consuming Packages Sometimes packages have not been packaged the way you expect, and you have to tweak the way webpack interprets them. Webpack provides multiple ways to achieve this. resolve.alias Sometimes packages do not follow the standard rules and their package.json contains a faulty main field. It can be mis…
  44. Extending Even though there are a lot of available loaders and plugins for webpack, it's good to be able to extend it. In this part, you go through a couple of short examples to understand how to get started. …
  45. Extending with Loaders As you have seen so far, loaders are one of the building blocks of webpack. If you want to load an asset, you most likely need to set up a matching loader definition. Even though there are a lot of available loaders, it's possible you are missing one fitting your purposes. You'll learn to develop …
  46. Extending with Plugins Compared to loaders, plugins are a more flexible means to extend webpack. You have access to webpack's compiler and compilation processes. It's possible to run child compilers, and plugins can work in tandem with loaders as MiniCssExtractPlugin shows. Plugins allow you to intercept webpack's execu…
  47. Conclusion As this book has demonstrated, webpack is a versatile tool. To make it easier to recap the content and techniques, go through the checklists below. General checklist Source maps** allow you to debug your code in the browser during development. They can also give better quality stack traces during…
  48. Appendices As not everything that's worth discussing fits into the main content, you can find related material in brief appendices. These support the primary content and explain specific topics, such as Hot Module Replacement, in greater detail. You will also learn to troubleshoot webpack. …
  49. Comparison of Build Tools Back in the day, it was enough to concatenate scripts together. Times have changed, though, and distributing your JavaScript code can be a complicated endeavor. This problem has escalated with the rise of single-page applications (SPAs) as they tend to rely on many big libraries. For this reason, m…
  50. Hot Module Replacement Hot Module Replacement (HMR) builds on top of the WDS. It enables an interface that makes it possible to swap modules live. For example, style-loader can update your CSS without forcing a refresh. Implementing HMR for styles is ideal because CSS is stateless by design. HMR is possible with JavaScr…
  51. CSS Modules Perhaps the most significant challenge of CSS is that all rules exist within global scope, meaning that two classes with the same name will collide. The limitation is inherent to the CSS specification, but projects have workarounds for the issue. CSS Modules introduces local scope for every module …
  52. Searching with React Let's say you want to implement a rough little search for an application without a proper backend. You could do it through lunr and generate a static search index to serve. The problem is that the index can be sizable depending on the amount of the content. The good thing is that you don't need th…
  53. Troubleshooting Using webpack can lead to a variety of runtime warnings or errors. Often a particular part of the build fails for a reason or another. A basic process can be used to figure out these problems: Enable stats.errorDetails in webpack configuration to get more information. Study the origin of the error…
  54. Glossary Given webpack comes with specific terminology, the principal terms and their explanations have been gathered below. Asset** is a general term for the media and source files of a project that are the raw material used by webpack in building a bundle. Bundle** is the result of bundling. Bundling inv…