Webpack from A to Asia: Code Splitting

Tram Ho

Webpack from A to Asia with kentrung

Code Splitting is one of the attractive features of webpack. This feature allows you to split your code into different packages, split the same code or library into a separate file. It can be used to separate smaller packages and control resource load priority which, if used properly, can have a big impact on a website’s load time.

1. Prepare the file

Add lodash library to create a common library, the files need to be called

Code file webpack.config.js

Code file src/home.js

Code file about.js

We see that both the file home.js and about.js above call the lodash library to create duplication.

2. Webpack Code Splitting

With the above setup and configuration without Code Splitting when we run npm run dev , the parameters are as follows:

We have two output files, about.js and home.js of 72KiB capacity

Now we add Code Splitting into the webpack.config.js file to separate the code

Rerun npm run dev and see the difference

At this point we can see that there are three output files, home.js about.js and vendors~about~home.js

The two output files: about and home previously had a capacity of 72KiB now only about 1.5KiB

The output file vendors~about~home.js that this means that webpack has optimized the source code, cleaned up the same libraries (lodash itself), the name is remixed between vendor (vendor) with two file names.

Note that when running through Code Splitting, the code has been split into different files. In the dist/index.html file that you want to run, you must call both files from vendors.

This article is over, hopefully with this article you have added a lot of useful knowledge. See you in the next article!

Share the news now

Source : Viblo