Easily Serving Hashed Webpack Bundles
Continuing with this Vue 2 extraction project, today I finally tackled something that's been slowing me down — manually updating hashed bundle names just to see my changes.
Previously, this injection of bundled scripts into HTML was handled automatically by the Razor pages in the .NET monorepo. Now that we've made this app standalone, we need a new solution.
Enter html-webpack-plugin. This plugin will automatically generate your HTML files and inject the correct bundled script. No more copy-pasting filenames.
npm install --save-dev html-webpack-pluginNote: This legacy app is currently running Webpack 4
Once installed, we need to tell Webpack to use this plugin by adding it to a plugins array in our config. Making sure we also require it:
const HTMLWebpackPlugin = require("html-webpack-plugin");
...
output: {
path: join.resolve(__dirname, "assets"),
filename: "[name].[contenthash].bundled.js",
},
plugins: [
new HTMLWebpackPlugin({
template: "index.html",
}),
],
...In this case, we already had an index.html file that pulled in a few additional scripts and assets. To make Webpack aware of it, pass it into the plugin configuration under the template property.
Now, when you run your builds, Webpack will generate a new index.html inside your configured output directory, automatically referencing the correct hashed bundle.
If you don't have a special template, you can simply omit this template property.
const HTMLWebpackPlugin = require("html-webpack-plugin");
...
output: {
path: join.resolve(__dirname, "assets"),
filename: "[name].[contenthash].bundled.js",
},
plugins: [
new HTMLWebpackPlugin(),
],
...Webpack will generate a basic index.html file for you that will look something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Webpack App</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<script src="your-webpack-bundle.bundled.js"></script>
</body>
</html>This small change eliminated a silly headache that was bottlenecking my workflow 🤘