Webpack4 插件实现原理与手写示例

作者:小满时间:2026-10-24 16:19:12浏览:392

本文深入解析 Webpack4 中 Plugin 的实现机制,通过源码分析 Compiler 类与 Tapable 的关系,阐述 hooks 事件流的创建与触发过程。结合同步与异步插件的模拟调用及文件说明插件的手写实践,帮助开发者掌握 Webpack 插件开发的核心流程与最佳实践。

前言

在 Webpack 中,除了 Loader 之外,核心功能便是 Plugin(插件)。Plugin 在 Webpack 执行过程中监听广播的一系列事件,并通过 Webpack API 对输出文件进行相应处理。例如 html-webpack-plugin 插件负责将模板文件 index.html 拷贝到 dist 目录。

认识

首先通过源码来了解 Plugin 的基本结构。参考 Webpack4 源码中 Compiler.js 的第 551 行代码。


// 创建一个编译器
createChildCompiler(
  compilation,
  compilerName,
  compilerIndex,
  outputOptions,
  plugins // 里边就有包含插件
) {

   // new 一个 编译器
  const childCompiler = new Compiler(this.context);
  // 寻找存在的所有 plugins 插件
  if (Array.isArray(plugins)) {
    for (const plugin of plugins) {
       // 如果存在, 就调用 plugin 的 apply 方法
      plugin.apply(childCompiler);
    }
  }
  
  // 遍历寻找 plugin 对应的 hooks
  for (const name in this.hooks) {
    if (
      ![
        "make",
        "compile",
        "emit",
        "afterEmit",
        "invalid",
        "done",
        "thisCompilation"
      ].includes(name)
    ) {
    
      // 找到对应的 hooks 并调用, 
      if (childCompiler.hooks[name]) {
        childCompiler.hooks[name].taps = this.hooks[name].taps.slice();
      }
    }
  }
 
 // .... 省略 ....

  return childCompiler;
}

从上述源码可以看出,Plugin 本质上是一个类。首先实例化一个 Compiler 类并传入当前上下文,接着判断插件是否存在,若存在则直接调用对应 Plugin 的 apply 方法,随后找到对应的 Plugin 调用的 hooks 事件流,并将事件发射给相应的 hooks。那么 hooks 是从哪里来的呢?

参考 Webpack4 源码中 Compiler.js 的第 42 行代码。


// 上述的 Compiler 类继承自 Tapable 类,而 Tapable 就定义了这些 hooks 事件流
class Compiler extends Tapable {
 constructor(context) {
            super();
            this.hooks = {
                    /** @type {SyncBailHook<Compilation>} */
                    shouldEmit: new SyncBailHook(["compilation"]),
                    /** @type {AsyncSeriesHook<Stats>} */
                    done: new AsyncSeriesHook(["stats"]),
                    /** @type {AsyncSeriesHook<>} */
                    additionalPass: new AsyncSeriesHook([]),
                    /** @type {AsyncSeriesHook<Compiler>} */
                    beforeRun: new AsyncSeriesHook(["compiler"]),
                    /** @type {AsyncSeriesHook<Compiler>} */
                    run: new AsyncSeriesHook(["compiler"]),
                    /** @type {AsyncSeriesHook<Compilation>} */
                    emit: new AsyncSeriesHook(["compilation"]),
                    /** @type {AsyncSeriesHook<string, Buffer>} */
                    assetEmitted: new AsyncSeriesHook(["file", "content"]),
                    /** @type {AsyncSeriesHook<Compilation>} */
                    afterEmit: new AsyncSeriesHook(["compilation"]),

                    /** @type {SyncHook<Compilation, CompilationParams>} */
                    thisCompilation: new SyncHook(["compilation", "params"]),
                    /** @type {SyncHook<Compilation, CompilationParams>} */
                    compilation: new SyncHook(["compilation", "params"]),
                    /** @type {SyncHook<NormalModuleFactory>} */
                    normalModuleFactory: new SyncHook(["normalModuleFactory"]),
                    /** @type {SyncHook<ContextModuleFactory>}  */
                    contextModuleFactory: new SyncHook(["contextModulefactory"]),

                    /** @type {AsyncSeriesHook<CompilationParams>} */
                    beforeCompile: new AsyncSeriesHook(["params"]),
                    /** @type {SyncHook<CompilationParams>} */
                    compile: new SyncHook(["params"]),
                    /** @type {AsyncParallelHook<Compilation>} */
                    make: new AsyncParallelHook(["compilation"]),
                    /** @type {AsyncSeriesHook<Compilation>} */
                    afterCompile: new AsyncSeriesHook(["compilation"]),

                    /** @type {AsyncSeriesHook<Compiler>} */
                    watchRun: new AsyncSeriesHook(["compiler"]),
                    /** @type {SyncHook<Error>} */
                    failed: new SyncHook(["error"]),
                    /** @type {SyncHook<string, string>} */
                    invalid: new SyncHook(["filename", "changeTime"]),
                    /** @type {SyncHook} */
                    watchClose: new SyncHook([]),

                    /** @type {SyncBailHook<string, string, any[]>} */
                    infrastructureLog: new SyncBailHook(["origin", "type", "args"]),

                    // TODO the following hooks are weirdly located here
                    // TODO move them for webpack 5
                    /** @type {SyncHook} */
                    environment: new SyncHook([]),
                    /** @type {SyncHook} */
                    afterEnvironment: new SyncHook([]),
                    /** @type {SyncHook<Compiler>} */
                    afterPlugins: new SyncHook(["compiler"]),
                    /** @type {SyncHook<Compiler>} */
                    afterResolvers: new SyncHook(["compiler"]),
                    /** @type {SyncBailHook<string, Entry>} */
                    entryOption: new SyncBailHook(["context", "entry"])
            };
            
            // TODO webpack 5 remove this
            this.hooks.infrastructurelog = this.hooks.infrastructureLog;
               
            // 通过 tab 调用对应的 comiler 编译器,并传入一个回调函数
            this._pluginCompat.tap("Compiler", options => {
                    switch (options.name) {
                            case "additional-pass":
                            case "before-run":
                            case "run":
                            case "emit":
                            case "after-emit":
                            case "before-compile":
                            case "make":
                            case "after-compile":
                            case "watch-run":
                                    options.async = true;
                                    break;
                    }
            });
            // 下方省略 ......
  }

了解了基本结构后,我们可以推断出 Plugin 的基本结构和用法,如下所示。


// 定义一个 plugins 类   
class MyPlugins {
    // 上边有说 new 一个编译器实例,会执行实例的 apply 方法,传入对应的 comiler 实例
    apply (compiler) {
        // 调用 new 出来 compiler 实例下的 hooks 事件流,通过 tab 触发,并接收一个回调函数
        compiler.hooks.done.tap('一般为插件昵称', (默认接收参数) => {
            console.log('进入执行体');
        })
    }
}
// 导出
module.exports = MyPlugins

OK,以上是一个简单的模板,我们来测试内部的钩子函数是否能如预期般被调用和触发。

配置 Webpack


let path = require('path')
let DonePlugin = require('./plugins/DonePlugins')
let AsyncPlugins = require('./plugins/AsyncPlugins')

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        filename: 'build.js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins: [
        new DonePlugin(),    // 内部同步 hooks
        new AsyncPlugins()   // 内部异步 hooks
    ]
}

同步 Plugin 插件模拟调用


class DonePlugins {
    apply (compiler) {
        compiler.hooks.done.tap('DonePlugin', (stats) => {
            console.log('执行: 编译完成');
        })
    }
}

module.exports = DonePlugins

异步 Plugin 插件模拟调用


class AsyncPlugins {
    apply (compiler) {
        compiler.hooks.emit.tapAsync('AsyncPlugin', (complete, callback) => {
            setTimeout(() => {
                console.log('执行:文件发射出来');
                callback()
            }, 1000)
        })
    }
}

module.exports = AsyncPlugins

最后编译 Webpack 可以看到编译控制台,分别打印出“执行:编译完成”和“执行:文件发射出来”,说明这样是可以调用到 hooks 事件流并且可以触发的。

实践出真知

了解了基本结构和使用方式后,现在来手写一个 Plugin 插件。嗯,就做一个文件说明插件吧。我们日常打包时,可以打包一个 xxx.md 文件到 dist 目录,作为打包说明。这里就实现这么一个小功能。

文件说明插件


class FileListPlugin {
    // 初始化,获取文件的名称
    constructor ({filename}) {
        this.filename = filename
    }
    // 同样的模板形式,定义 apply 方法
    apply (compiler) {
        compiler.hooks.emit.tap('FileListPlugin', (compilation) => {
            // assets 静态资源,可以打印出  compilation 参数,还有很多方法和属性
            let assets = compilation.assets;
            
            // 定义输出文档结构
            let content = `## 文件名  资源大小\r\n`
            
            // 遍历静态资源,动态组合输出内容
            Object.entries(assets).forEach(([filename, stateObj]) => {
                content += `- ${filename}    ${stateObj.size()}\r\n`
            })
            
            // 输出资源对象
            assets[this.filename] = {
                source () {
                    return content;
                },
                size () {
                    return content.length
                }
            }
            
        })
    }
}
// 导出
module.exports = FileListPlugin

Webpack 配置


let path = require('path')
let HtmlWebpackPlugin = require('html-webpack-plugin')
// plugins 目录与node_modules 同级, 自定义 plugins , 与 loader 类似
let FileListPlugin = require('./plugins/FileListPlugin')

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        filename: 'build.js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html'
        }),
        new FileListPlugin({
            filename: 'list.md'
        })
    ]
}

OK,通过以上配置,我们在打包时可以看到,每次打包在 dist 目录中都会出现一个 xxx.md 文件,而这个文件的内容就是我们上面定义的 content。

到此这篇关于浅谈 Webpack4 plugins 实现原理的文章就介绍到这了,更多相关 Webpack4 plugins 内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!

作者最新文章