Code Splitting in Webpack 1 - Basics
The Problem
We all know that deploy a gigantic bundle.js
with our app is not a good option. Because the first page should be loaded as fast as possible. Otherwise the user will leave the app. We, developer, should consider to use any possible options to reduce the initial loading time.
Luckily, webpack
got you covered!
The Solution
The solution webpack
used is called code splitting
. It’s splitting the code into different parts (webpack
‘s term is called chunk
). So the individual page will only need to load the parts it needs. If some parts are already loaded, it will only load the missing part, which is much quicker.
The technique webpack
uses is to splitting the code when it meets the splitting point. What’s a splitting point? It varies based on the module system you are using:
- for
commonjs
, it’srequire.ensure(dependencies, callback)
- for
AMD
, it’srequire(dependencies, callback)
- for
SystemJS
, it’sSystem.import(dependencies)
The Example
Let’s take a look at thecode-splitting
example from webpack
repo.
Inside node_modules
folder, we have 4 files, each one represents a module like we used in everyday development. Outside the node_modules
folder, we have a example.js
:
|
|
- Load module
a
- Load module
b
- Here comes the
require.ensure()
, it tellswebpack
that from this point, we need another chunk to separate the code. This code should include modulec
- In the new chunk, load module
b
; - in the new chunk load module
d
So if we use the following configuration:
|
|
and we run command webpack
(if you already installed webpack
globally), we should get result similiar to the following:
|
|
As we expected, the output are 2 files:
output.js
is the initial chunk, which needs to be loaded first. It contains modulea
andb
. The rest is thewebpack
polyfill.This will normally be the
js
file in your app’s index page.0.output.js
contains modulec
andd
. In our analysis, it should containb
as well, butb
has already been loaded sowebpack
is smart enough to remove it.This will normally be the
js
file in your app’s other page, loaded by routing system.
There are other tricks to do the code-splitting as well. We’ll look at them in following posts.
Stay tuned!