Here a simple htmlWebpackPlugin is implemented to help us understand the running mechanism of plugin.
htmlWebpackPlugin
HtmlWebpackPlugin is used to generate an HTML file at packaging time and import the output JS file into the script tag.
The code is as follows:
class HtmlWebpackPlugin {
constructor(options = {}) {
this.options = options;
}
apply(compiler) {
// When Webpack registers the plugin, it executes its apply method
const pluginName = HtmlWebpackPlugin.name;
const { RawSource } = compiler.webpack.sources;
// Tapping to the "thisCompilation" hook in order to further tap
// to the compilation process on an earlier stage.
compiler.hooks.thisCompilation.tap(pluginName, (compilation) = > {
const outputJSFile = compilation.options.output.filename;
const ouputContent = `
<html>
<head>
<meta charset="utf-8" />
<title>Webpack App</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<script defer="defer" src="${outputJSFile}"></script>
</head>
<body></body>
</html>
`;
// Tapping to the assets processing pipeline on a specific stage.
compilation.hooks.processAssets.tap(
{
name: pluginName,
},
() = > {
compilation.emitAsset('index.html'.new RawSource(ouputContent)); // Add a new asset}); }); }}module.exports = { HtmlWebpackPlugin };
Copy the code
Introduce the following in webpack.config.js:
const { HtmlWebpackPlugin } = require('./plugins/htmlWebpackPlugin');
module.exports = {
entry: './src/index.js'.output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',},plugins: [new HtmlWebpackPlugin()], / / introduce HtmlWebpackPlugin
};
Copy the code
Note that the Plugin needs to implement a Apply method in which you can subscribe to events (WebPack’s event publishing subscription is based on Tapable) and set up a callback function that fires at a particular phase of the WebPack run.
See Writing a Plugin.