Multiple html files using webpack
To use Multiple HTML files in Webpack
using HtmlWebpackPlugin :
Modify the
webpack.config.js
by directly embedding the below code.
const HtmlWebpackPlugin = require('html-webpack-plugin');
let htmlPageNames = ['example1', 'example2', 'example3', 'example4'];
let multipleHtmlPlugins = htmlPageNames.map(name => {
return new HtmlWebpackPlugin({
template: `./src/${name}.html`, // relative path to the HTML files
filename: `${name}.html`, // output HTML files
chunks: [`${name}`] // respective JS files
})
});
module.exports = {
entry: {
main: './js/main.js',
example1: './js/example1.js',
//... repeat until example 4
},
module: {
//.. your rules
};
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
chunks: ['main']
})
].concat(multipleHtmlPlugins)
};
You can add as many HTML pages as required to the htmlPageNames
array. Ensure that each HTML and corresponding JS file have the same name (The above code assumes that).
See an entrypoint as the root of a tree that references many other assets like javascript modules, images, templates and so on. When you define more than one entrypoint, you basically split your assets into so called chunks to not have all your code and assets in one single bundle.
What I think you want to achieve is to have more than one "index.html" for different apps that also refer to different chunks of your assets which you already defined with your entrypoints.
Copying an index.html file or even generating one with references to these entrypoints is not handled by the entrypoint mechanism - it is the other way round. A basic approach for handling html pages is using the html-webpack-plugin
which not only can copy html files but also has an extensive mechanism for templating. This is especially helpful if you want to have your bundles suffixed with a bundle hash that is pretty to avoid browser caching issues when you update your app.
As you have defined a name pattern as [id].bundle_[chunkhash].js
you can no longer reference your javascript bundle as main.bundle.js
as it will be called something like main.bundle_73efb6da.js
.
Have a look at the html-webpack-plugin. Especially relevant for your use case:
- Generating multiple html files
- Filtering chunks
You should probably have something like that in the end (warning: not tested)
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html',
chunks: ['main']
}),
new HtmlWebpackPlugin({
filename: 'example.html',
template: 'src/example.html',
chunks: ['exampleEntry']
})
]
Please be aware to reference the name of the entrypoint in the chunks array, so in your example this should be exampleEntry
. Probably it's also a good idea to move your templates into a specific folder instead of having them in directly inside the root src folder.
Hope this helps.