如何自定义webpack插件

目标实现  移除 webpack 注释

webpack要求插件必须是一个函数或者是一个包含apply方法的对象

创建你的插件

class MyPlugin {
    apply (compiler) {
        console.log("MyPlugin Start")
        //emit 钩子
        compiler.hooks.emit.tap('MyPlugin', compilation => {
            // console.log('compilation--------', compilation)
            //compilation 此次打包的上下文
            for(const name in compilation.assets){
                // console.log(name)
                // console.log(compilation.assets[name].source())

                if(name.endsWith('.js')){
                    const contents = compilation.assets[name].source()

                    const withoutComments = contents.replace(//**+*//g, '')

                    compilation.assets[name] = {
                        source: () => withoutComments,   //内容覆盖
                        size: () => withoutComments.length  //必须返回
                    }
                }
            }
        })
    }
}

实现:    插件是通过webpack生命周期的钩子中挂载函数实现扩展

原文地址:https://www.cnblogs.com/faint33/p/14899465.html