Multi-page applications

Bharat Tiwari
A beginner’s guide to Webpack 2
3 min readMay 7, 2017

--

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:

(click on image to see in expanded popover view)

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.js

c. 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 and app.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 and settings.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.

(click on image to see in expanded popover view)

./dist/index.html — generated by HtmlWebpackPlugin with two embedded <script> tags — for the two files app.bundle.js and vendor.bundle.js.

(click on image to see in expanded popover view)

./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.

(click on image to see in expanded popover view)

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:

(click on image to see in expanded popover view)

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.

--

--