欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > webpack自定义plugin

webpack自定义plugin

2025/3/21 5:39:46 来源:https://blog.csdn.net/qq_40121308/article/details/146297046  浏览:    关键词:webpack自定义plugin

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文件尾部添加注释效果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词