/ webpack

Three Webpack 2 Speed Improvements

Since moving to webpack 2 I've been building out more complex apps than ever before. All I mean by this is, multiple dynamic imports are used across my app. Initially this was causing a 5 second delay on every file save. I've gotten it down to 1-2 seconds by doing three easy things.

Don't transpile async-await in development

If you're using the latest version of Chrome in development, it supports this natively, so I switched up my .babelrc to this:

{
  "env": {
    "production": {
      "presets": [
        ["es2015", {"loose": true, "modules": false}],
        "react",

        "stage-2"
      ],
      "plugins": [
        "transform-react-inline-elements",

        "transform-decorators-legacy",
        "transform-flow-strip-types",
        "syntax-dynamic-import"
      ]
    },
    "development": {
      "presets": [
        ["es2015", {"loose": true, "modules": false}],
        "react"
      ],
      "plugins": [
        "react-hot-loader/babel",
        "transform-class-properties",
        "transform-object-rest-spread",

        "transform-decorators-legacy",
        "transform-flow-strip-types",
        "syntax-dynamic-import"
      ]
    }
  }
}

Removing stage 2 from development will remove all of that processing.

More specific imports

I have a system in place that will load a corresponding language file with a route. This means each route can have multiple split points depending on the amount of language files:

// loading a component
import(`../../views/${pathFinder(path)}`);

// language files
try {
    return await import(`site/${pathFinder(path)}/${language}`);
  } catch (e) {
    return await import(`site/${pathFinder(path)}/en-us`);
  }

By simply adding .js to the end of those import statements, it's given another compile time boost. Before, it would look for any files, and even though nothing else was there, I imagine .DS_Store and other possible hidden files were being added to webpack's context.

Adding in Happypack

Changing the loaders section in webpack to use happypack has also helped a lot. It allows builds to happen in parallel across multiple threads. The config is simple, add something like this to your plugins list:

new HappyPack({
  id: 'js',
  threads: 4,
  loaders: ['babel-loader', 'eslint-loader'],
}),
new HappyPack({
  id: 'css',
  threads: 4,
  loaders: ['style-loader', 'css-loader'],
})

Then add the loader:

{
    test: /\.js$/,
    loaders: 'happypack/loader?id=js',
    exclude: /node_modules/,
    include: resolve(__dirname, '../modules'),
},

These three things helped me reduce build times tremendously. Hopefully this can help someone else out there. If anyone has ideas on speeding up webpack 2 even more, I'd love to hear about it.