Search code examples
javascriptreactjsconsolebabeljsconsole.log

Remove console log statements in react production build?


I have a basic react app (created using create react app)
I have gone through a few links related such as babel plugin installation npm i babel-plugin-transform-remove-console --save Guide to remove console log using babel plugin

 {
  "env": {
    "production": {
      "plugins": ["transform-remove-console"]
    }
  }
}

I have included the above config to babel.rc file but still, it doesn't solve my problem. I am able to see the logs in the production build. Kindly let me know where I am going wrong.


Solution

  • You could try this, in src/App.js, the root component of your app:

    if (process.env.NODE_ENV === "production")
      console.log = function no_console() {};
    

    Just before the return.

    edit: thanks to @Youngmu Yang for the correction. It's weird but in my case was the .env that I put before, the complete answer should be:

    if (process.env['The_env_of_your_project_that_defines_environment'] === "production")
      console.log = function no_console() {};