• 0

Webpack CommonsChunkPlugin, HtmlWebpackPlugin Setup

In this example, we will show you the capabilities of webpack's commonsChunkPlugin. It is such an important feature of webpack that I ended up recording a video.

Code splitting with webpack's CommonsChunkPlugin, html-webpack-plugin!
[youtube https://youtu.be/qPHlCDOzCEk]

Single Entry Point

[wpgist id="1a27e3207c6ecaf87220cc765ffb6257" file="single-entry.js"] Note the followings :
  • entry - We have a single entry point in Router.jsx
  • output - Instruct webpack to create bundle.js from our single entry point
  • new HtmlWebpackPlugin - Generates the index.html file and injects the following script tag in it
<script type="text/javascript" src="build.js"></script>

Mutiple Entry Points

[wpgist id="1a27e3207c6ecaf87220cc765ffb6257" file="mutiple-entry-points.js"] Note the followings :
  • entry - Instructs webpack to generate two bundles namely app, vendor
  • output - Instructs webpack to generate output bundle with the dynamic names. Here, it will generate the following bundles
app-[chunkhask].js
vendor-[chunkhash].js
  • new CommonsChunkPlugin - Instructs webpack to extract the common modules from the app, vendor entry points and generate a bundle with commons-[hash].js name which can be referred as commons at other places.

  • new HtmlWebpackPlugin - Generates index.html file and injects the following script tags in it

<script type="text/javascript" src="app-[chunkhash].js"></script>
<script type="text/javascript" src="commons-[chunkhash].js"></script>

Further Reading


If you find this post useful and want us to write more about webapck let us know by leaving your feedback in the comments.