自定义 loader 去删除全局console.log

思路就是,拿到代码中所有的 console.log(xxx),并对其进行删除,webpack 的 loader 本质上其实就是一个函数,我们可以在这个函数内部,根据正则匹配出我们想删除的字符串,对其进行替换。

自定义 loaders/ignore-console-log-loader.js 代码很简单,如下:

const reg = /(console.log\()(.*)(\))/;
gmodule.exports = function (sourceCode) {
    
     
  return sourceCode.replace(reg, '');
}

使用姿势,在webpack.config.js 配置文件中添加一下自定义的 loader :

module: {
    
      
 rules: [   
  {
    
       test: /\.js$/,    
      loader: ['ignore-console-log-loader'],   
   },  
  ] 
 }, 
resolveLoader: {
    
      // 指定自定义 loader 的位置目录  
 modules: ['node_modules', path.resolve(__dirname, 'loaders')] 
 },

另外使用UglifyJsPlugin 也可以,但是看网上很多采坑报错的文章,这种简单的自己写一下 更好, 加深webpack理解。

猜你喜欢

转载自blog.csdn.net/Beth__hui/article/details/113956343