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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//example.js
import a from "a"; //1
System.import("b").then(function(b) { //2
console.log("b loaded", b);
})
function loadC(name) {
return System.import("c/" + name) //3
}
Promise.all([loadC("1"), loadC("2")]).then(function(arr) { //4
console.log("c/1 and c/2 loaded", arr);
});

We’ll take a closer look at each step:

  1. load module a using ES6 syntax import
  2. load module b, but here we define our splitting point by usingSystem.import()
  3. create a function loadC() using System.import() inside, which means whenever we use this function, we want webpack to generate a separate chunk for us.
  4. inside Promise.all(), we call function loadC() twice.

So if we run the command webpack and use the following configuration:

1
2
3
4
5
6
7
8
//webpack.config.js
module.exports = {
entry: './example.js',
output: {
path:'./js/',
filename:'output.js'
}
}

we should get a result similar to the following output:

1
2
3
4
5
6
7
8
9
10
Hash: 0bdf6f6d99c782a6ec70
Version: webpack 2.1.0-beta.25
Time: 125ms
Asset Size Chunks Chunk Names
0.output.js 91 bytes 0 [emitted]
1.output.js 91 bytes 1 [emitted]
2.output.js 89 bytes 2 [emitted]
output.js 6.54 kB 3 [emitted] main
[5] ./example.js 269 bytes {3} [built]
+ 5 hidden modules

We now have 4 files generated by webpack:

  • output.js is the entry chunk, which will be loaded first. It contains example.js and a.
  • 0.output.js includes c2
  • 1.output.js includes c1
  • 2.output.js includes b

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!