webpack

What is the right way to configure multiple pages in Webpack?


I'm trying to create a basic website using just Webpack. My purpose is to have a simple URL structure like example.com/about, example.com/contact.

In Webpack, I can use HTMLWebpackPlugin, but I need to create an instance for every route. So, my question is: is there a way to simplify this?

const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/main.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    devServer: {
        port: 5000,
    },
    plugins: [
        new htmlWebpackPlugin({
            title: 'Home',
            filename: 'index.html',
            template: './src/pages/home/index.html',
        }),
        new htmlWebpackPlugin({
            title: 'About',
            filename: 'about/index.html',
            template: './src/pages/about/index.html',
        }),
    ],
};

Solution

  • You Webpack config file is javascript. So you could add some helper functions to abstract the process and eventually just plug in an array of pages that will produce the desired effect:

    const htmlWebpackPlugin = require('html-webpack-plugin');
    
    const generateHtmlPlugin = (title) => {
      return new htmlWebpackPlugin({
        title,
        filename: 'index.html',
        template: `./src/pages/${title.toLowerCase()}/index.html`,
      });
    }
    
    const populateHtmlPlugins = (pagesArray) => {
      res = [];
      pagesArray.forEach(page => {
        res.push(generateHtmlPlugin(page));
      })
      return res;
    }
    

    So this is not too much code, and it will allow you to just insert an array of your desired pages when setting up webpack:

    const pages = populateHtmlPlugins(["About", "Articles", "Users", "Contact"]);
    
    module.exports = {
      //...
      plugins: pages
    }
    

    Better yet, you can create a utils folder and refactor the code into two exported modules, then just import populateHtmlPlugins() in your webpack config file and stay very clean.

    Now you can create as many pages as you want easily enough.