webpack插件 照葫芦画瓢

115 阅读1分钟

明白插件触发时机

Webpack 提供钩子有很多,这里简单介绍几个,完整具体可参考文档《Compiler Hooks》

  • entryOption: 在webpack 选项中的entry 配置项处理过之后,执行插件。
  • afterPlugins : 设置完初始插件之后,执行插件。
  • compilation : 编译创建之后,生成文件之前,执行插件。
  • emit : 生成资源到 output 目录之前。
  • done : 编译完成。

compiler.hooks下的事件钩子函数,触发钩子时,执行回调函数

Webpack 提供三种触发钩子的方法:

  • tap :以同步方式触发钩子;
  • tapAsync :以异步方式触发钩子;
  • tapPromise :以异步方式触发钩子,返回 Promise;

最终实现一个 替换指定文件内容到 输出html 中。

/**
 * 读取shell 下的内容然后拼接到dist/html里
 *
 */
const path = require("path");
const fs = require("fs");
let _shellPath = null;

class copySkeletonPlugin {
  constructor(option) {
    if (option) {
      _shellPath =
        path.resolve(process.cwd(), "./shell") +
        `\\${option.entryKey.replace(/\//g, "")}.html`;
    }
    console.log(_shellPath);
  }
  apply(compiler) {
    if (compiler) {
      compiler.hooks.compilation.tap(
        "copySkeletonPlugin",
        (compilation, callback) => {
          compilation.plugin(
            "html-webpack-plugin-before-html-processing",
            (htmlPluginData, callback) => {
              htmlPluginData.html = htmlPluginData.html.replace(
                "<!-- shell -->",
                insertHTMLToDist(htmlPluginData)
              );
            }
          );
        }
      );
    }
  }
}
// 读取文件内容
function insertHTMLToDist() {
  let fileData = "";
  if (fs.existsSync(_shellPath)) {
    fileData = fs.readFileSync(_shellPath, "utf-8");
    return fileData;
  }
  return fileData;
}

module.exports = copySkeletonPlugin;

3-10 年内部岗位涉及前后端、PM(虾皮内推、乐信内推、vivo、oppo)推荐机会,欢迎联系,wx号: X915324 ; 也可发简历到: zgxie@126.com