Harnessing the power of Webpack
We are overwhelmed by the response on our previous blog about Housing Go and today we are sharing our bundling and chunking strategies using webpack.
TL; DR;
- Use code splitting and create multiple entry points.
- Extract common chunks from entry-points mentioned in 1.
- Use `recordsPath` option for long-term caching.
1. Use code splitting and create multiple entry points
Code splitting
For big web apps it’s not efficient to put all code into a single file, especially if some blocks of code are only required under some circumstances. Webpack has a feature to split your codebase into “chunks” which are loaded on demand. Some other bundlers call them “layers”, “rollups”, or “fragments”. This feature is called “code splitting”.
To clarify a common misunderstanding: Code Splitting is not just about extracting common code into a shared chunk. The more notable feature is that Code Splitting can be used to split code into an on demand loaded chunk. This can keep the initial download small and downloads code on demand when requested by the application.
Multiple entry points
If you need multiple bundles for multiple HTML pages you can use the “multiple entry points” feature. It will build multiple bundles at once. Additional chunks can be shared between these entry chunks and modules are only built once.
Source: https://webpack.github.io/docs/multiple-entry-points.html
2. Extract common chunks from entry-points
A common challenge with combining [chunkhash] and Code Splitting is that the entry chunk includes the webpack runtime and with it the chunkhash mappings. This means it’s always updated and the [chunkhash] is pretty useless, because this chunk won’t be cached.
A very simple solution to this problem is to create another chunk which contains only the webpack runtime (including chunkhash map). This can be archieved by the CommonsChunkPlugin (or if the CommonsChunkPlugin is already used by passing multiple names to the CommonChunkPlugin). To avoid the additional request for another chunk, this pretty small chunk can be inlined into the HTML page.
Source: https://github.com/webpack/webpack/tree/master/examples/chunkhash
For more understanding read our webpack configuration explanation CommonsChunksPlugin techniques by Sean T. Larkin
3. Use `recordsPath` option for long-term caching
For Housing Go’s webpack configuration — read here
Must read:
- Webpack and caching — Explanation on caching strategies from the author of webpack, Tobias Koppers
- Webpack issue#1315 thread — It is an open issue, still you might find a solution if you are facing anything related to extracting or caching chunks.
Future work
We will be trying out some exciting things with webpack 2.0 and will post our learnings here soon.
If you want to read the full story about our journey to Progressive Web Application, checkout this blog post.