Blog

My Log

Webpack Multiple HTML Page Generate

Here is the sample of file structure with the webpack.

Here is the code for webpack.config.js:

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

//generate html pages
function generateHtmlPages(templateDir) {
  const templateFiles = fs.readdirSync(path.resolve(__dirname, templateDir));

  return templateFiles.map(function (item) {
    const parts = item.split('.');
    const name = parts[0];
    const extension = parts[1];

    return new HtmlWebpackPlugin({
      filename: `${name}.${extension}`,
      template: path.resolve(__dirname, `${templateDir}/${name}.${extension}`),
    });
  });
}

const htmlPages = generateHtmlPages('./src/templates');

module.exports = {
  entry: {
    main: './src/index.js',
  },

  plugins: [].concat(htmlPages),
}