美文网首页
自定义webpack插件

自定义webpack插件

作者: 三省吾身_9862 | 来源:发表于2019-02-26 09:59 被阅读4次
// 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: ''})
]

相关文章

  • electron之使用两个package.json

    要自定义生成electron的package.json没有现成的webpack插件,需要自己写一个 插件代码 we...

  • webpack插件指南

    webpack 有着丰富的插件接口。webpack 自身的多数功能都使用插件接口。插件接口使 webpack 变得...

  • vue项目中配置全局常量

    使用webpack插件webpack.DefinePlugin设置全局常量,可减少某些操作。 在webpack插件...

  • Webpack4-Plugins

    插件(Plugins) 插件是 webpack 的支柱功能。webpack 自身也是构建于,你在 webpack ...

  • 自定义webpack插件

    事件:通过执行下列事件来允许其他插件更改html:异步事件:html-webpack-plugin-before-...

  • webpack使用

    webpack的插件 代码压缩 如果不需要自定义压缩的参数,可以使用./node_modules/.bin/web...

  • webpack将资源打成zip包

    webpack插件:filemanager-webpack-plugin 该插件允许你复制,打包,移动,删除文件及...

  • webpack插件& loader篇

    插件 webpack入门中 列出了下面这些插件 本篇则对它们做一个介绍 插件分文webpack内置插件 和 要外部...

  • 为webpack编写一个plugin

    0、基本概念 插件是webpack的支柱功能,极大地强化了webpack的构建能力。 webpack 插件由以下组...

  • (转)使用webpack.DllPlugin与webpack.D

    解决webpack打包速度太慢使用webpack插件webpack.DllPlugin与webpack.DllRe...

网友评论

      本文标题:自定义webpack插件

      本文链接:https://www.haomeiwen.com/subject/ljvoyqtx.html