There are multiple reasons why you would want several bundles for your application. It might be that you have several pages and you don't want each page to load a heavy bundle, but only the JavaScript that it needs. You might also want to separate third-party libraries from the app itself. Let's try to look at how we could create several bundles.
Our ideal scenario is that we want three different files, app.js, init.js, and vendor.js:
-
-
init.js: This should contain what the bundles have in common, that is, our webpack runtime
-
vendor.js: This is where the third-party libraries we are dependent on live, such as query and lodash
To accomplish this, we need to change the configuration file to say the following:
module.exports = {
entry : {
app: "./app.js",
vendor: ["angular"]
},
output: { filename : "[name].js" },
watch: true,
plugins: [
new Webpack.HotModuleReplacementPlugin(),
new Webpack.optimize.CommonsChunkPlugin("init")
]
}
Let's break that down:
entry: {
app: "./app.js",
vendor: ["angular"]
}
We used to have one entry here pointing to app.js. Now we want to have two entries, but for different things. Vendor points to an array of libraries. This means that when webpack sees a:require('angular'),
The second piece of interest is:
plugins: [ new Webpack.optimize.CommonsChunkPlugin('init') ]
Here we are saying to take everything we have in common (the webpack runtime in this case) and place it in init.js.