Multi-page applications
What if we have a multi-page app? Lets say, we have two html files — index.html
and settings.html
. index.html uses app.js and settings.html might be using settings.js
Again, we can specify multiple entry points in webpack.config to output multiple bundles.
Also, we need to add one more instance of HtmlWebpackPlugin (we learnt HtmlWebpackPlugin in one of the previous lessons) in the plugins array for it to generate settings.html for us:
1. Under ‘./src/scripts’ folder, add a new file settings.js:
2. Update the webpack.config.js
as below:
Again, lets go over the changes we made above in webpack.config.js
:
a. Line#8 - we added an additional key settings in
entry
to tell webpack to create an additional bundle for settings.js and its dependencies.b. In the plugins array, we added another instance of HtmlWebpackPlugin (line#24) with filename =
‘./dist/settings.html’
and template =‘./src/index.html’
. This would create settings.html for us using the same template ‘index.jsc. Note the new ‘chunks’ property we added in each HtmlWebpackPlugin instance (line# 21 and 29)
In the first instance, which is for index.html, we are adding ‘vendor’ and ‘app’ chunks. This means, the HtmlWebpackPlugin wound insert <script> tags for each of these two chunks i.e.vendor.bundle.js
andapp.bundle.js
Similary, the second instance, which is for settings.html, we added ‘vendor’ and ‘settings’ chunks, so that it would have the <script> tags for
vendor.bundle.js
andsettings.bundle.js
3. Run npm start
for webpack to run with the updated config options.
$ npm start
4. This time you would notice webpack created three expected bundled files in the ‘dist’ folder — app.bundle.js, vendor.bundle.js and settings.bundle.js.
HtmlWebpackPlugin created two html files viz. index.html and settings.html.
./dist/index.html
— generated by HtmlWebpackPlugin with two embedded <script> tags — for the two files app.bundle.js and vendor.bundle.js.
./dist/settings.html
— generated by HtmlWebpackPlugin with two embedded <script> tags — for the two files vendor.bundle.js and settings.bundle.js.
5. In the browser, the index.html
would remain the same as we didn’t make any change to it.
6. Open the newly created settings.html
in the browser, the message logged to console in 'settings.js'
should be visible in the browser console:
In the next lesson, we’ll learn how to use webpack to take out the common code shared by multiple modules in our app and put it in common chunks. This is perhaps one of the most significant benefit of using webpack.