Code Splitting in Webpack 2 - ES6
In part 1, we take a look at example using commonjs
. In this part, we will look at how we do code splitting using ES6 syntax.
webpack
v1 doesn’t support ES6 syntax without a compiler like babel
, so there’s no way to use code splitting in v1. But with webpack
v2, you can write ES6 code without any compiler. And webpack
can not only understand it but provide more functionalities, such as tree-shaking.
In this post, we will only focus on the code splitting.
The example
The example is taken from webpack
repo.
|
|
We’ll take a closer look at each step:
- load module
a
using ES6 syntaximport
- load module
b
, but here we define our splitting point by usingSystem.import()
- create a function
loadC()
usingSystem.import()
inside, which means whenever we use this function, we wantwebpack
to generate a separate chunk for us. - inside
Promise.all()
, we call functionloadC()
twice.
So if we run the command webpack
and use the following configuration:
|
|
we should get a result similar to the following output:
|
|
We now have 4 files generated by webpack
:
output.js
is the entry chunk, which will be loaded first. It containsexample.js
anda
.0.output.js
includesc2
1.output.js
includesc1
2.output.js
includesb
The chunks’ content is kind of random, which means it may contains different module than I showed here. But that should not be a problem.
Next time, we will see how to extract css
file into a separate chunk.
Stay tuned!