preface

During Web project development, we often output a lot of logs from the console via console.log for debugging purposes, but usually we need to block it when the project goes live. The WebPack configuration helps us do this.

1. Write ignore the console – log – loader. Js

We create a loaders folder under node_modules, which holds all the custom Loader files for the project. Ignore-console-log-loader. js simply replaces console.log with an empty string

//ignore-console-log-loader.js
const reg = /console\.log\(.*\)/g;
module.exports = function (srcCode) {
    return srcCode.replace(reg, ' ');
}
Copy the code

2. Configure the vue. Config. Js

ConfigureWebpack: configureWebpack: configureWebpack: configureWebpack: configureWebpack: configureWebpack: configureWebpack:

 // If the value is an object, it is merged into the final configuration by webpack-merge.
 // If the value is a function, the parsed configuration is accepted as an argument. This function can modify the configuration and return nothing, or it can return a cloned or merged version of the configuration.
  configureWebpack: {
   resolveLoader: {
      modules: ['node_modules'.'./loaders/']}}Copy the code

We then add the custom loader to config.module using the config object exposed in the chainWebpack function. We add the environment variable determination using the config.when() method, which takes two arguments. The second argument is the callback method, which fires only if the first argument is true

 // chainWebpack is a function that takes an instance of a ChainableConfig based on webpack-chain. Allows for more fine-grained changes to the internal WebPack configuration.
  chainWebpack(config) {
    // Customize loader to clear console
    config.when(
      process.env.NODE_ENV === 'production'.config= >
      config.module.
        rule('js')
        .test(/\.js$/)
        .use('ignore-console-log-loader')
        .loader('ignore-console-log-loader')
        .end()
    )
Copy the code

3. The conclusion

The configuration of a custom loader is not complicated, but it will still have a lot of harvest to write. I hope this article can help people in need.