For example say there is a scenario where you would like to change the title text in the template file. Our template file is a simple Html file with a title tag. For this you can create a custom plugin, in the plugin logic fetch the html content of the template file and use simple string function like replace to change the text.
First off, you should be familiar with webpack configuration file, check out – https://webpack.js.org/ to learn about webpack. Also plugins section to add or define a plugin https://webpack.js.org/configuration/plugins/.
Below is the code example.
module.exports = {
//...
plugins: [
new HtmlWebpackPlugin({
"template": "./index.html",
"filename": "./newIndex.html",
...
}),
new CustomTemplatePlugin(),
],
};
In above code we are using the html-webpack-plugin to create the template (Html) file for the webpack bundle. After this plugin is finished our custom plugin is invoked (CustomTemplatePlugin) and here we are using the events (hooks) from the HtmlWebpackPlugin to fetch the Html content and make changes.
Below is code sample for the custom plugin.
const HtmlWebpackPlugin = require("html-webpack-plugin");
function CustomTemplatePlugin(options) {
options = options || {};
}
CustomTemplatePlugin.prototype.apply = function(compiler) {
compiler.hooks.compilation.tap("CustomTemplatePlugin", (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync("CustomTemplatePlugin", (htmlPluginData, cb) => {
const fileName = htmlPluginData.plugin.options["filename"];
if (fileName && fileName.indexOf("index") > -1) {
htmlPluginData.html = htmlPluginData.html.replace(/Loading.../, "Hello World");
}
cb(null, htmlPluginData);
});
});
};
In above code of our custom plugin we are using getHooks static function on the HtmlWebpackPlugin to add event listener (tabAsync). In the listener we are making the change as per our requirement. We are changing the text Loading… in the title tag of our Html file to Hello World.
Below is our simple Html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Loading...</title>
</head>
<body>
</body>
</html>
Now when you run the webpack we should see our new Html file in the bundle i.e newIndex.html and title tag should have Hello World.