如何自定義webpack外掛
阿新 • • 發佈:2021-06-18
目標實現 移除 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生命週期的鉤子中掛載函式實現擴充套件