Background
Many people are using Webpack in front-end projects to pack their modules, especially for big single page application. Usually, it will pack up all your js files into one js bundle., but you may not need them all at the same time since it will take longer when the page is being loaded.
So, this post will focus on how to make it possible to dynamically import modules. Before reading this post, experience in Webpack and Webpack loaders is required.
Prerequisite
You will need to have Node and NPM installed on your machine to go through the following examples.
Use require.ensure instead of require
The require.ensure method ensures that every dependency can be asynchronously imported when calling the callback. An implementation of the require function is sent as a parameter to the callback. It helps you to load your bundles on demand.
Example:
In the ES6 world, you can also write your code as below,. The only thing you need to do is to install “babel-plugin-dynamic-import-webpack” to make sure the syntax is recognized by your babel-loader.
Add chunk hash to your js chunk
Chunk hash is used to resolve the browser cache issue. After you change the JavaScript file, the js file name is not changed so the browser regards it as unchanged and then loads it from the browser cache.
After you add chunkhash to your JS file name, every time it is changed, hash is calculated based on the compilation. For sure, it will be different from the codes of the last version. Thus browser is informed that the file name has been changed and it knows that “oh, I have to load it again!”.
Example:
Split app and vender code
We usually would like to split 3rd party codes out of our app codes and make them as long-term-caching in the browser. This is a good practice when using Webpack, because 3rd party codes usually stay the same. It’s not a good idea to combine them together with our codes of business logic.
Example:
Use the CommonsChunkPlugin to split runtime codes of Webpack
After you split your vendor code and app code, there are some runtime codes for Webpack in vendor.js. Once you change your app code, you will find your vendor’s chunk hash is still changing and the browser will load it from the server instead of cache. To avoid this, you need to use the CommonsChunkPlugin to split them from the vendor.
After Webpack is finished, you can find a new JavaScript file is generated and it includes all Webpack runtime codes.
Example:
Use HtmlWebpackPlugin to automatically inject your js chunk
As you have already finished all of the code splitting work, you need to inject your js file into your page template. HtmlWebpackPlugin will automatically include your webpack bundles with the hash name.
Example:
Conclusion
To enable your js dynamical import and long-term-cache though Webpack:
- ensure/import().then
- generate hash file name
- code splitting
- auto injecting
Hope you enjoy it!