Customize loader to delete global console.log

The idea is to get all console.log(xxx) in the code and delete it. The loader of webpack is essentially a function. We can match the string we want to delete according to the regularity inside this function. Replace it.

The custom loaders/ignore-console-log-loader.js code is very simple, as follows:

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

Using the posture, add a custom loader to the webpack.config.js configuration file:

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

In addition, UglifyJsPlugin can also be used, but if you look at many articles on the Internet that report errors in mining pits, it is better to write it yourself and deepen your understanding of webpack.

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/113956343