自定義webpack插件

// 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-chunkscss

配合htmlWebpackPlugin插件,給html中link標籤加id

my-plugin.jshtml

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 中配置爲:webpack

let MyPlugin = require('./my-plugin.js')
// ...
plugins: [
  new MyPlugin({options: ''})
]
複製代碼
相關文章
相關標籤/搜索