An experiment to see how Webpack's import()
module method can be used to split code and how that can affect the bundle size.
Running npm start initialises an isomorphic React app at localhost:3000
(and optionally the Webpack Bundle Analyzer at localhost:8888
- needs to be enabled in webpack config).
Default bundle without any optimisation da2ef00
Basic code splitting using import()
c696a0f
The two split bundles combined size is actually larger than the original. See src/universal/app.js
for an example of code splitting. The SomeOtherComponent
bundle is only requested when the user clicks on the button.
Common chunks extracted: 845a9e3
Using the CommonsChunkPlugin
to extract libraries in to a separate chunk. Starting to see some improvements in bundle sizes:
Using the WebpackBundleAnalyzer
showed that SomeOtherComponent
bundle size was mainly comprised of lodash
. Reduce the size of this by only importing what we need from lodash
27ea766
-
Uglification 4fc6cf7
-
Build for production environment 293a509
-
Gzip bundles using Webpack's Compression plugin 39a0c45. Further reducers file sizes but requires the server to be configured to serve gzipped assets. I've used NGINX for this.
(Currently it seems there is an issue with the compression plugin not producing compressed versions of bundles that are dynamically imported. There is an open issue on github here: webpack-contrib/compression-webpack-plugin#79)
In a real-world app there are other techniques that can be used to further reduce bundle size. They don't really make any difference in the context of this tiny example app:
- Extract CSS in to separate files
- Control how sourcemaps are generated in your production build using the Devtool option (this can have a big impact on bundle size)
- Dead code elimination with Tree Shaking
- Replace the React.createElement function with babelHelpers using Babel's transform-react-inline-elements plugin
- Agressive Merge plugin
- Module Concatentation Plugin