自定义webpack插件

2019-02-26  本文已影响4人  三省吾身_9862
// 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: ''})
]
上一篇 下一篇

猜你喜欢

热点阅读