Webpack multiple HTML - I need only to inject one .js for each HTML

Viewed 160

Hi I have the following problem with my Webpack Config:

I want to have 3 different .js files from my src folder. Each file is supposed to be connected to only the corresponding html file with the same name:

Example: I want app.html only to inject app.js and not index.js and register.js as well.

As for now, Webpack generates 3 html files and 3 .js files, however every .html file gets referenced all 3 .js files, which breaks my code, since I don't have the corresponding id's for eventlisteners in index that the code written app.js.

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

module.exports = {
    entry: {
        index: ['./src/js/index.js'],
        register: ['./src/js/register.js'],
        app: ['./src/js/app.js'],
    },
    output: {
        filename: '[name].js',
        path: __dirname + '/dist',
    },
    devServer: {
        contentBase: './dist'
    },
   
    plugins: [
        new HtmlWebpackPlugin({
            inject: true,
            chunks: 'index',
            template:'./src/index.html',
            filename: './src/index.html'
        }),
        new HtmlWebpackPlugin({
            inject: true,
            chunks: 'register',
            template:'./src/register.html',
            filename: './src/register.html'
        }),
        new HtmlWebpackPlugin({
            inject: true,
            chunks: 'app',
            template:'./src/app.html',
            filename: './src/app.html'
        })
    ],
    

    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            }
        ]
    }
};

1 Answers

Here you have an example adding one chunks to the html

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

const config = [{
  site: 'index'
}, {
  site: 'register'
}, {
  site: 'app'
}];

const entryHtmlPlugins = config.map(({
  site
}) => {
  return new HtmlWebPackPlugin({
    filename: `${site}.html`,
    chunks: [site],
  });
});

module.exports = {
  mode: 'production',
  entry: {
    index: './src/js/index.js',
    register: './src/js/register.js',
    app: './src/js/app.js',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, './dist'),
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
      },
    }, ],
  },
  plugins: [...entryHtmlPlugins],
};
Related