📜 ⬆️ ⬇️

Script Optimization with Webpack SplitChunksPlugin

In this article I would like to share my experience on splitting bundles for a multi-page site using Webpack 4. First, we will create our own entry point for each page. Consider the example of 4 pages:


const path = require("path"); const PATHS = { src: path.resolve(process.cwd(), "src"), dist: path.resolve(process.cwd(), "dist") }; module.exports = { entry: { common: `${PATHS.src}/js/common`, index: `${PATHS.src}/js/index`, contacts: `${PATHS.src}/js/contacts`, about: `${PATHS.src}/js/about`, } } 

At assembly for each page the bandl will be created. I put common scripts for all pages to the common entry point. To connect our bundles to the pages, we will use the Webpack plugin HtmlWebpackPlugin .


Consider an example:


  module.exports = { ... plugins: [ new HtmlWebpackPlugin({ filename: `${PATHS.dist}/index.html`, template: `${PATHS.dist}/index.html`, chunks: ["index", "common"] }) ... ] ... }; 

In the chunks indicate the bundles necessary for this page (sequence: from right to left). Thus, the page will be connected first with common scripts, and then the scripts needed separately for this page.


If we have common modules / third-party libraries connected on different pages, we will create common bundles for these pages.


Use Webpack plugin SplitChunksPlugin . Actually here is the configuration:


 module.exports = { optimization: { splitChunks: { chunks: "all", minSize: 1, minChunks: 2 } } } 

After the assembly, we will get bundles separately for each page and bundles that divide our pages.


 index.js contacts.js common.js about.js vendors~about-us~index.js vendors~about-us~contacts.js 

In the vendors ~ about-us ~ index.js bundle, common scripts for about-us and index will be submitted, which will be cached by the browser, and when switching from the page to about will be already downloaded by the browser, and you will only need to download the bundle about.js .


The names of the chunks can be changed in the config of this plugin.


To connect these bundles correctly for each of our pages we will use HtmlWebpackPlugin. The configuration is the same as in the beginning of the article. Only here you will have to install an alpha version of this plugin, because at the time of this writing, this plugin did not connect our shared chunks, but only connected entry points.


 npm i --save-dev html-webpack-plugin@next 

After the build, we will get this code in index.html:


 <script src="js/common.js"></script> <script src="js/vendors~about-us~index.js"></script> <script src="js/index.js"></script> 


Source: https://habr.com/ru/post/441076/