Skip to content
Advertisement

Multiple HtmlWebpackPlugins with webpack DevServer

You can use multiple HtmlWebpackPlugin plugins to create more than one HTML file in production, but only one of the HTML files will be used by the DevServer. Is there any way to use all the HtmlWebpackPlugin plugins in development as well?

module.exports = {
  entry: {
    main: './src/main.js',
    anotherEntry: './src/anotherEntry.js'
  },
  // This only serves the index.html file on 404 responses
  devServer: {
    contentBase: './dist',
    historyApiFallback: true,
    port: 3000,
  },
  // ...
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/main.html',
      chunks: ['main'],
    }),
    new HtmlWebpackPlugin({
      filename: 'anotherEntry.html',
      template: './src/anotherEntry.html',
      chunks: ['anotherEntry'],
    }),
  ]
};

Advertisement

Answer

historyApiFallback can be given manual rewrites to control in a more fine-grained manner what the DevServer should fallback to on 404 responses. This way we can serve the other files in development as well.

module.exports = {
  entry: {
    main: './src/main.js',
    anotherEntry: './src/anotherEntry.js'
  },
  devServer: {
    contentBase: './dist',
    historyApiFallback: {
      rewrites: [
        { from: /^/anotherEntry/, to: '/anotherEntry.html' },
        { to: '/index.html' },
      ],
    },
    port: 3000,
  },
  // ...
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/main.html',
      chunks: ['main'],
    }),
    new HtmlWebpackPlugin({
      filename: 'anotherEntry.html',
      template: './src/anotherEntry.html',
      chunks: ['anotherEntry'],
    }),
  ]
};
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement