Search code examples
javascriptwebpack-4html-webpack-plugin

A clean way to loop HTMLWebpackPlugin with Webpack?


I'm using Webpack 4 with the HTMLWebPackPlugin. I'm currently at the point where I am dealing with close to 30 different pages and more moving forward. Here is a sample of what I have in code...

        new HTMLWebpackPlugin({
            template: './src/game11/index.html',
            mViewPort: 'width=device-width, initial-scale=1.0',
            favicon: './src/game11/media/favicon-16x16.png',
            title: 'Game 11 Training',
            filename: 'game11.htm',
            chunks: ['game11']
        }),
        new HTMLWebpackPlugin({
            template: './src/game12/index.html',
            mViewPort: 'width=device-width, initial-scale=1.0',
            favicon: './src/game12/media/favicon-16x16.png',
            title: 'Game 12 Training',
            filename: 'game12.htm',
            chunks: ['game12']
        }),

I have 30 of these so far in my webpack.config.js file. But I would prefer to do something like this instead...

 ['game11','game12','something-else','etc'].forEach((event) => {
       new HtmlWebpackPlugin({
           template: './src/${event}/index.html',
           mViewPort: 'width=device-width, initial-scale=1.0',
           favicon: './src/${event}/media/favicon-16x16.png',
           title: '${event} Training',
           filename: '${event}.htm',
           chunks: ['${event}']
       }),
   }),

The above code does not work and it only a sketch. But is it possible to do something like that today without adding additional plugins or modifying my outputs? I simply want to add array values which will create a new instance in itself.

Many thanks!


Solution

  • Following the same logic you suggested on your question, you could use map instead of forEach to build the plugins array like so:

    webpack.config.js

    {
      plugins: [
        new MiniCSSExtractPlugin(),
        ...['game11', 'game12', 'something-else', 'etc'].map((event) => {
          return new HtmlWebpackPlugin({
            template: `./src/${event}/index.html`,
            mViewPort: `width=device-width, initial-scale=1.0`,
            favicon: `./src/${event}/media/favicon-16x16.png`,
            title: `${event} Training`,
            filename: `${event}.htm`,
            chunks: [`${event}`]
          })
        })
      ]
    }