Webpack – Split app, vendor and polyfill builds

It makes sense when you are working with a building tool like webpack to separate the app build from the vendor and polyfill builds. The main objective of this approach is to improve the payload of our site by allowing the browser to request only the code that changes, probably app code, and not code that is almost never going to change, like third-party libraries and frameworks. You create only one bundle with all the code.

Application vendor file

The first thing that we need to do, is to import all the vendors into a single vendor file. This file is going to be the vendor bundle entry point. In an angular project the vendor file would like something like this;

 

Application polyfill file

The other file that we need to add is a polyfill file that is going to contain all our polyfills and is going to be the entry file for the webpack polyfill bundle. In an angular project it may look something like this;

In your application code, you use the imports as always directly from the vendor’s libraries or frameworks.

Webpack configuration

In order to make webpack create the three bundles, we need to add some configuration to our webpack config file.

  1.  We need to configure three entry files.
    In order to make this happen, we need to set the three entry point file for each of the bundles that we want to create. In our case, we have three: polyfills, vendor, and app.
  2. We need to configure the output to create the three bundles
    Take into consideration that by using the [name] inside the filename configuration you are going to get a file for each of the property’s names set in the entry configuration. In our case, the output is going to create a polyfill.bundle.js, a vendor.bundle.js, and an app.bundle.js.

  3. We need to tell webpack to use these files and not to add the already imported vendors to the app bundle.
    Webpack is not smart enough to figure out by itself already-handled dependencies in different files. So to resolve this we need to use the CommonsChunkPlugin. This plugin identifies shared dependencies between the files and removes them from app bundle. Setting it up is quite simple; inside the plugins section of webpack add:

Conclusion

This approach is quite simple to set and the win is big because we are improving the payload of our application by allowing the browser to improve and actually take advantage of the caching of files.

 

Webpack - Separate app, vendor and polyfill builds.






Santiago Garcia Da Rosa