Instead of html-webpack-plugin you can use the modern powerful html-bundler-webpack-plugin.
All script and style source files (js, ts, css, scss, etc.) can be specified directly in the HTML template using <script> and <link> tags.
The plugin resolves source files of assets in templates and replaces them with correct output URLs in the generated HTML.
The resolved assets will be processed via Webpack plugins/loaders and placed into the output directory.
Using the bundler plugin:
- An entry point is an HTML template.
- Binding the source script/style filenames directly in HTML using
<script> and <link>.
- Resolving source asset files specified in attributes
href src srcset etc.
- Inline JS, CSS, SVG, PNG without additional plugins and loaders.
- Support for any templating engine (Eta, EJS, Handlebars, Nunjucks, LiquidJS, etc.).
For example, there is the HTML template:
<html>
<head>
<!-- relative path to SCSS source file -->
<link href="../scss/style.scss" rel="stylesheet" />
<!-- relative path to TypeScript source file -->
<script src="../app/main.js" defer="defer"></script>
</head>
<body>
<h1>Hello World!</h1>
<!-- relative path to image source file -->
<img src="../assets/images/picture.png" />
</body>
</html>
Minimal Webpack config:
const path = require('path');
const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new HtmlBundlerPlugin({
entry: {
index: 'src/views/index.html', // save generated HTML into dist/index.html
},
js: {
filename: 'js/[name].[contenthash:8].js', // JS output filename
},
css: {
filename: 'css/[name].[contenthash:8].css', // CSS output filename
},
}),
],
module: {
rules: [
{
test: /\.s?css$/,
use: ['css-loader', 'sass-loader'],
},
{
test: /\.(ico|png|jp?g|svg)/,
type: 'asset/resource',
},
],
},
};
The generated HTML contains hashed output URL of assets:
<html>
<head>
<link href="css/style.1234abcd.css" rel="stylesheet" />
<script src="js/main.ab32dc41.js" defer="defer"></script>
</head>
<body>
<h1>Hello World!</h1>
<img src="ab12cd34.png" />
</body>
</html>