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.
//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:
- load module
ausing 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 wantwebpackto 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:
//webpack.config.js
module.exports = {
entry: './example.js',
output: {
path:'./js/',
filename:'output.js'
}
}
we should get a result similar to the following output:
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.jsis the entry chunk, which will be loaded first. It containsexample.jsanda.0.output.jsincludesc21.output.jsincludesc12.output.jsincludesb
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!