7

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.

  • 3
    If you used create-react-app it might not be paying attention to your custom babel config, since it has all its own configs. You may need to eject the app in order to get this to work. – Dr_Derp Jul 26 '19 at 16:54
  • Take a look at https://github.com/facebook/create-react-app/issues/2730 and https://github.com/kentcdodds/babel-plugin-macros – Fraction Jul 26 '19 at 17:10
  • @Dr_Derp Looking for a way where we can accomplish without ejecting the app. – Vigneshwaran Markandan Aug 02 '19 at 11:14
  • 1
    Without ejecting: https://stackoverflow.com/questions/47839311/removing-log-statements-in-create-react-app-without-ejecting – Christiaan Westerbeek Sep 06 '19 at 18:15

3 Answers3

4

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() {};
pmiranda
  • 7,602
  • 14
  • 72
  • 155
1

@pmiranda 's solution should be changed to:

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

You can try those packages to override the config:

Note: from the document of react-app-rewired, this would break the the "guarantees" that CRA provides. So you should be careful before using it.

npm i -D customize-cra react-app-rewired babel-plugin-transform-remove-console

Modify your package.json, replace react-scripts to react-app-rewired except the reject. Once complete, your scripts should look like this:

"scripts": {
 "start": "react-app-rewired start",
 "build": "react-app-rewired build",
 "test": "react-app-rewired test",
 "eject": "react-scripts eject"
}

Then create a file:

touch config-overrides.js
// config-overrides.js
const { override, addBabelPlugins } = require('customize-cra')

module.exports = override(
  addBabelPlugins(
    "transform-remove-console"
  )
)

Finally, after run npm run build, all console.log will be removed.

Also, I have another answer regarding this similar question, you can check out other answers as well.

Kaiwen Luo
  • 370
  • 4
  • 10