webpack5 plugin原理

125 阅读4分钟

plugin原理

plugin的作用

通过插件我们可以扩展webpack,加入自定义的扩展行为,使webpack可以执行更广泛的任务,拥有更强的构建能力。

plugin工作原理

webpack就像一条生产线,要经过一系列处理流程后才能将源文件转换成输出结果。这条生产线上的每个处理流程的职责都是单一的,多个流程之间有存在依赖关系,只有完成当前处理后才能交给下一个流程去处理。插件就像是一个插入到生产线中的一个功能,在特定的时机对生产线上的资源做处理。webpack通过Tapable来组织这条复杂的生产线,webpack在运行过程中会广播事件,插件只需要监听它所关心的事件,就能加入到这条生产线中,去改变生产线的运作。webpack的事件机制保证了插件的有序性,使得整个系统扩展性很好。——[深入浅出Webpack] 站在代码逻辑的角度就是:webpack在编译过程中,会触发一系列 Tapable 钩子事件,插件所做的,就是找到自己的钩子,往上面挂上自己的任务,也就是注册事件,这样,当webpack构建的时候,插件注册的事件就会随着钩子的触发执行了。

webpack内部的钩子

什么是钩子

钩子的本质就是事件。为了方便我们直接介入和控制编译过程,webpack把编译过程中触发的各类关键事件封装成事件接口暴露了出来,这些接口被形象地称作hooks(钩子)。开发插件,离不开这些钩子。

Tapable

Tapable为webpack提供了统一的插件接口类型定义,它是webapck的核心功能库,webpack中目前有十种hooks,在tapable源码中可以看到。
Tapable还统一暴露了3个方法给插件:

  • tap 可以注册同步钩子和异步钩子
  • tapAsync 回调方式注册异步钩子
  • tapPromise Promise方式注册异步钩子

plugin构建对象

Compiler

compiler中保存着完整的webpack环境配置,每次启动webpack构建时它都是一个独一无二仅仅会创建一次的对象。
这个对象会在首次启动webpack时创建,我们可以通过compiler对象访问到webpack的主环境配置,比如loader, plugin等配置信息。
它有以下主要属性:

  • compiler.options 可以访问本次启动webpack时候所有的配置文件,包括但不限于loaders, entry, output, plugins等等完整配置信息。
  • compiler.inputFileSystem 和 compiler.outputFileSystem 可以进行文件操作,相当于node.js中的fs.
  • compiler.hooks 可以注册tapable的不同种类hook,从而可以在compiler生命周期中植入不同的逻辑

Compilation

compilation对象代表一次资源的构建,compilation实例可以访问所有的模块和他们的依赖。
一个compilation对象会对构建依赖图中所有模块进行编译。在编译阶段,模块会被加载(load),封存(seal),优化(optimize),分块(chunk),哈希(hash)和重新创建(restore)。 它有以下主要属性:

  • compilation.modules 可以访问所有模块,打包的每一个文件都是一个模块。
  • compilation.chunks chunk即是多个modules组成而来的一个代码块。入口文件引入的资源组成一个chunk,通过代码分割的模块又是另一个chunk。
  • compilation.assets 可以访问本次打包生成的所有文件的结果。
  • compilation.hooks 可以注册tapable的不同种类hook,用于在compilation编译模块阶段进行逻辑添加以及修改。

最简单的插件

/**
 * 1. webpack加载webpack.config.js中所有配置,此时就会 new Terser(), 
 * 执行插件的constructor
 * 2. webpack创建compiler对象
 * 3. 遍历plugins中所有插件,调用插件的apply方法
 * 4. 执行剩下编译流程(触发各个hooks事件)
 */
class TerserPlugin {
    constructor(){

    }
    apply(compiler){

    }                                           
}
module.exports = TerserPlugin

注册hooks

class TerserPlugin {
    constructor() {

    }
    apply(compiler) {
        compiler.hooks.environment.tap('TerserPlugin', () => { })
        // emit注册了多个事件 异步串行 AsyncSeriesHook
        conpiler.hooks.emit.tap('TerserPlugin', (compilation) => {

        })
        conpiler.hooks.emit.tapAsync('TerserPlugin', (compilation, callback) => {
            setTimeout(() => {
                callback()
            }, 1000)
        })
        conpiler.hooks.emit.tapPromise('TerserPlugin', (compilation) => {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve()
                }, 1000)
            })
        })
        // 由文档可知,make是异步并行钩子 AsyncParallelHook
        compiler.hooks.make.tapAsync('TerserPlugin', (compilation, callback) => {
            // 需要在compilation hooks触发前注册才能使用
            compilation.hooks.seal.tap('TerserPlugin', () => {

            })
        })
    }
}
module.exports = TerserPlugin

BannerWebpackPlugin

/**
 * 给打包输出文件添加注释
 * 1. 需要打包输出前添加注释:需要使用compiler.hooks.emit钩子,它是打包输出前触发。
 * 2. 如何获取打包输出的资源?compilation.assets可以获取即将输出的文件资源。 
 */
class BannerWebpackPlugin {
    constructor(options = {}) {
        this.options = options
    }
    apply(compiler) {
        compiler.hooks.emit.tapAsync('BannerWebpackPlugin', (compilation, callback) => {
            const extensions = ['js', 'css'];
            const assets = Object.keys(compilation.assets).filter((assetPath) => {
                const splitted = assetPath.split('.');
                const extension = splitted[splitted.length - 1];
                return extensions.includes(extension)
            })
            const prefix = `/*
* Author: ${this.options.author}
*/        
`
            assets.forEach(asset => {
                const source = compilation.assets[asset].source();
                const content = prefix + source;
                //修改资源
                compilation.assets[asset] = {
                    source() {

                        return content
                    },
                    size() {
                        return content.length
                    }
                }
            })
            callback();
        })
    }
}
module.exports = BannerWebpackPlugin;

CleanWebpackPlugin

/**
 * 在webpack打包输出前将上次打包内容清空
 * 1. 如何在打包输出前执行?需要使用compiler.hooks.emit钩子,它是打包输出前触发
 * 2. 如何清空上次打包内容?
 *    获取打包输出目录 通过compiler对象
 *    通过文件操作清空内容 通过compiler.outputFileSystem操作文件
 */
class CleanWebpackPlugin {
    apply(compiler) {
        const outputPath = compiler.outputPath || compiler.options.output.path;
        const fs = compiler.outputFileSystem;
        compiler.hooks.emit.tap('CleanWebpackPlugin', (compilation) => {
            this.removeFiles(fs, outputPath)
        })
    }
    removeFiles(fs, filepath) {
        // 想要删除打包输出目录下的所有资源,需要先将目录下的资源删除,才能删除这个目录
        const files = fs.readdirSync(filepath); // ['images', 'index.html', 'js']
        files.forEach(file => {
            const path = `${filepath}/${file}`;
            const fileStat = fs.statSync(path);
            if (fileStat.isDirectory) {
                this.removeFiles(fs, path)
            } else {
                fs.unlinkSync(path)
            }
        });
    }
}
module.exports = CleanWebpackPlugin

AnalyzeWepackPlugin

/**
 * 分析webpack打包资源大小,并输出分析文件
 * 在哪做?compiler.hooks.emit, 它是在打包输出前触发我们需要分析资源大小同时添加上分析后的md文件
 */
class AnalyzeWebpackPlugin {
    apply(compiler) {
        compiler.hooks.emit.tap('AnalyzeWebpackPlugin', (compilation) => {
            const assets = Object.entries(compilation.assets);
            let content = `| 资源名称 | 资源大小 |
| --- | --- |`;
            assets.forEach(([filename, file]) => {
                content += `\n| ${filename} | ${Math.random(file.size() / 1024)}kb |`
            })
            compilation.assets["analyze.md"] = {
                source() {
                    return content
                },
                size() {
                    return content.length;
                }
            }
        })
    }
}

InlineChunkWebpackPlugin

/**
 * webpack打包生成的runtime文件太小了,额外发送请求性能不好,所以需要将其内联到js中去,从而减少请求数量
 * 1. 我们需要借助html-webpack-plugin来实现
 *    在html-webpack-plugin输出index.html前将内联runtime注入进去
 *    删除多余的runtime文件
 * 2. 如何操作html-webpack-plugin
 */
const HtmlWebpackPlugin = require('safe-require')('html-webpack-plugin');
class InlineChunkWebpackPlugin {
    constructor(tests) {
        this.tests = tests
    }
    apply(compiler) {
        compiler.hooks.compilation.tap('InlineChunkWebpackPlugin', (compilation) => {
            const hooks = HtmlWebpackPlugin.getHooks(compilation);
            hooks.alterAssetTagGroups.tap('InlineChunkWebpackPlugin', (assets) => {
                assets.headTags = this.getInlineChunk(assets.headTags, compilation.assets);
                assets.bodyTags = this.getInlineChunk(assets.bodyTags, compilation.assets)
            })
            // 删除runtime文件
            hooks.afterEmit.tap('InlineChunkWebpackPlugin', () => {
                Object.keys(compilation.assets).forEach(filePath => {
                    if (this.tests.some(test => test.test(filePath))) {
                        // if (/runtime(.*)\.js$/g.test(filePath)) {
                        delete compilation.assets[filePath]
                    }
                })
            })
        })
    }
    getInlineChunk(tags, assets) {
        return tags.map(tag => {
            if (tag.tagName !== 'script') return tag;
            const filePath = tag.attributes.src;
            if (!filePath) return tag;
            if (!this.tests.some(test => test.test(filePath))) return tag;
            if (!/runtime(.*)\.js$/g.test(filePath)) return tag;
            return {
                tagName: 'script',
                innerHTML: assets[filePath].source(),
                closeTag: true
            }
        });
    }
}