Syed Hammed
Syed Hammed

Reputation: 151

How to bundle js in html with webpack?

I am bundling my project with webpack. I want to bundle two times a javascript file in two separate html files. How can this be achieved?

My folder structure as follows

dist

 |- index1.html

 |- index2.html

 |- js

 |- index1.bundle.js

 |- index2.bundle.js

webpack.config.js

Here is the webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    index: './src/js/index.js',
    index2: './src/js/index2.js'
  },
  output: {
    filename: './js/[name].bundle.js'
  },
  watch: true,
  plugins: [
    new HtmlWebpackPlugin({
      hash: true,
      template: './src/index.html',
      filename: './index.html'
    }),
    new HtmlWebpackPlugin({
      hash: true,
      template: './src/index2.html',
      filename: './index2.html'
    })
  ]
};

How can I bundle the same file in two separate html files?

Upvotes: 2

Views: 2327

Answers (1)

Syed Hammed
Syed Hammed

Reputation: 151

Had figured it out. All I had to do was chunking.

I had to add

chunk: ['index'] for the first htmlwebpackplugin and

chunk: ['index2'] for the second htmlwebpackplugin

updated webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    index: './src/js/index.js',
    index2: './src/js/index2.js'
  },
  output: {
    filename: './js/[name].bundle.js'
  },
  watch: true,
  plugins: [
    new HtmlWebpackPlugin({
      hash: true,
      template: './src/index.html',
      filename: './index.html',
      chunks: ['index']
    }),
    new HtmlWebpackPlugin({
      hash: true,
      template: './src/index2.html',
      filename: './index2.html',
      chunks: ['index2']
    })
  ]
};

Upvotes: 2

Related Questions