Today I Learned

A Hashrocket project

Code splitting with Webpack 2 and Babel

Webpack 2 provides the ability to split your code into smaller files that are lazy loaded during runtime as they are needed.

When I first learned about this feature I thought it would be very intelligent in detecting which parts of the code are using a certain module and split all my modules into separate files automatically. That's not really the case.

If you want to have Webpack split your code and lazy load it you need to explicitly call import in your code. For example:

import Foo from './foo';

class Bar {
  baz() {
    Foo.someMethod(); // this will not be split and lazy loaded

    import('./lazy_module').then(function(lazyModule) {
    }).catch(function(err) {
      console.log('Failed to load lazy module', err);

To have this work you need to install the Syntax Dynamic Import library

Then edit your .babelrc:

  "presets": [["es2015", { "modules": false }]],
  "plugins": ["syntax-dynamic-import"]

The modules: false part is really important. It basically instructs Babel to not try and parse the imports but let Webpack 2's native ability to parse imports to do the work. This was tricky.

There's more to that and it keeps changing so I recommend visiting this documentation