webpack自定义plugin

发布于:2025-03-21 ⋅ 阅读:(23) ⋅ 点赞:(0)

plugin概念

plugin是用于bundle文件的优化,资源管理和环境变量注入等一系列的任务。作用于构建过程,插件可以用来执行范围更广的任务,如打包优化、资源管理和环境变量的注入。简单来说,插件可以用于执行任何其他loader无法完成的任务。它们直接作用于整个构建过程,从打包优化和压缩,一直到重新定义环境中的变量等。

使用webpack.BannerPlugin打包文件添加头注释

webpack.config.js配置

const path = require('path')
const webpack = require('webpack')
module.exports = {
    mode: 'development', // 指定环境
    entry: './src/index.js', // 入口
    output: { // 出口
        path: path.resolve(__dirname, './dist'),
        filename: 'bundle.js'
    },
    plugins: [
        new webpack.BannerPlugin({
            banner: '欢迎学习自定义webpack'
        }),
    ]
}

执行npm run build 后bundle.js文件头部成功添加注释
在这里插入图片描述

自定义 FooterPlugin实现bundle.js尾部添加注释

webpack.config.js配置

const path = require('path')
const FooterPlugin = require('./plugin/FooterPlugin')

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'bundle.js'
    },
    plugins: [
        new FooterPlugin({
            banner: '测试测试测试测试'
        })
    ]
}

FooterPlugin文件

const { ConcatSource } = require('webpack-sources')

class FooterPlugin {
    constructor(options) {
        console.log('FooterPlugin', options)
        this.options = options
    }

    apply(compiler) {
        compiler.hooks.compilation.tap('FooterPlugin', compilation => {
            compilation.hooks.processAssets.tap('FooterPlugin', () => {
                for(const chunk of compilation.chunks) {
                    for(const file of chunk.files) {
                        console.log('file', file)
                        const comment = `/* ${this.options.banner} */`
                        compilation.updateAsset(file, old => new ConcatSource(old, '\n', comment))
                    }
                }
            })
        })
    }
}

module.exports = FooterPlugin

bundle.js文件尾部添加注释效果
在这里插入图片描述