webpack自定义loader和自定义插件

1.封装自定义的功能loader

(格式很简单,重点在于loader-utils,loaderUitls.getOptions可获取webpack配置rules中的options以供使用 )

这只是一个简单的替换路径loader,具体别的需求的loader就可以自己编写内容了

 

 2.

compiler和compilation
// 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: ''})
]

猜你喜欢

转载自www.cnblogs.com/ygunoil/p/12094517.html