/ code

Separating vendor libraries using webpack

Previously I wrote an article about why you need to separate your vendor libraries from your application code. TL;DR: it's to make the browser save up bytes during assets updates so the browser doesn't have to download unchanged source code that most of time comes from vendor libraries like react.

Now here's the fun part: playing with it.

Playing with it.

Of course we are using webpack. Webpack provides many ways to optimize your code. Uglifying, code splitting, type-checking, and one of them is splitting and utilizing vendor libraries that comes from different file (one that was split). Yes, we are going to use webpack.optimize.CommonsChunkPlugin. I assume you are already comfortable in toying with webpack configuration file and how it works. So if you are still new-ish to this, I recommend you to step it up first by reading this.

Webpack configuration

Now typically you would configure webpack by using babel transpiler and maybe some css loaders, but this won't add much and won't make you break your current configuration (promise!). This is for webpack@^3.0.0.

// webpack.config.js
entry: {
  app: ...,
  vendor: [ // create new entry point
    // list all packages you want to separate to vendor-only file
 plugins: [
   new webpack.optimize.CommonsChunkPlugin({ // on plugins section, insert this
     name: 'vendor',
     /* name of the chunk. note that it must be
        the same as the entry point's name above. it's "vendor" */
     filename: 'vendor.bundle.js'
     /* the name of file that will be generated
        and must be loaded in the html */

See? It was only a few lines and surely it won't break your current webpack configuration. If you haven't used any webpack plugins before, make sure that plugins section is on the same depth as the entry section.

Including it in the HTML

It is as simple as the title says. Just include it using <script> tag and you are good to go!

<!-- index.html -->
<script src="vendor.bundle.js"></script>
<!-- remember to match the name in webpack.config.js -->

Now the browser will load both app.js and vendor.bundle.js. But, when app.js is changed, the browser will only re-download the application code instead of both application code and vendor libraries. The page performance is much faster!