首先我们要知道plugin是一个函数或者是一个包含apply方法的对象
接下来我们就自己去写一个plugin去清除代码中的注释,我们要清除bundle.js文件中的注释,所以我们要在bundle,js的内容明确了之后我们采取实施相应的动作.
通过官网查询找到emit这个钩子函数其执行时机是webpack即将要往输出目录输出文件时执行,非常符合需求
const MyPlugin = {
apply(compiler){
compiler.hook.emit.tap('MyPlugin ',compilation => {
//所有打包后的结果都会放到compilation这个对象中
for(let name in compilation){
if(name,endsWith('.js')){
const contents = compilation.assets[name].source()
const withoutComments = contents.replace(/\/\*\*+\*\//g,'')
compilation.assets[name] = {
source:() => withoutComments,
size:() => withoutComments.length
}
}
}
}.)
}
}