// MyPlugin.js
function MyPlugin(options) {
this.options = options;
}
MyPlugin.prototype.apply = function(compiler) {
// ...
compiler.plugin('compilation', function(compilation) {
console.log('The compiler is starting a new compilation...');
compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) {
htmlPluginData.html += 'The magic footer';
callback(null, htmlPluginData);
});
});
};
module.exports = MyPlugin;
事件:
通过执行下列事件来允许其他插件更改html:
异步事件:
html-webpack-plugin-before-html-generation
html-webpack-plugin-before-html-processing
html-webpack-plugin-alter-asset-tags
html-webpack-plugin-after-html-processing
html-webpack-plugin-after-emit
同步事件:
html-webpack-plugin-alter-chunks
配合htmlWebpackPlugin插件,给html中link标签加id
my-plugin.js
function MyPlugin(options) {
this.options = options;
}
MyPlugin.prototype.apply = function(compiler) {
compiler.plugin('compilation', function(compilation) {
compilation.plugin('html-webpack-plugin-alter-asset-tags', function(htmlPluginData, callback) {
if (htmlPluginData.head && htmlPluginData.head.length) {
htmlPluginData.head.forEach(item => {
if (item.attributes) {
let href = item.attributes.href;
item.attributes.id = href.substring(href.indexOf('css/') + 4, href.indexOf('.'));
}
});
}
callback(null, htmlPluginData);
});
});
};
module.exports = MyPlugin;
然后 webpack.config.js 中配置为:
let MyPlugin = require('./my-plugin.js')
// ...
plugins: [
new MyPlugin({options: ''})
]
网友评论