37

How can remove console.log in the production build of a React application created using create-react-app CRA?

Ajay
  • 1,255
  • 1
  • 17
  • 30
  • Self-answered questions must still be posted as a question and answer, and both must meet the quality requirements for any post. Also, why does this need another Q&A pair given that it's already in the one you've linked to? – jonrsharpe May 23 '19 at 13:28
  • Since faced issue in applying the solution in my app created using the create-react-app so I write it to help others – Ajay May 23 '19 at 13:38
  • 1
    Nonetheless, please at least split it to a Q and A. – jonrsharpe May 23 '19 at 13:38
  • Thanks, @jonrsharpe for the suggestion. Hope this is the correct split now. – Ajay May 23 '19 at 13:50

7 Answers7

50

I am using this approach to avoid ejecting react-scripts

if (process.env.NODE_ENV === 'production') {
  console.log = () => {}
  console.error = () => {}
  console.debug = () => {}
}

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import './styles/main.scss'

// replace console.* for disable log on production
if (process.env.NODE_ENV === 'production') {
  console.log = () => {}
  console.error = () => {}
  console.debug = () => {}
}

ReactDOM.render(<App />, document.getElementById('root'))
Ali Turki
  • 1,265
  • 2
  • 16
  • 21
8

I created a helper folder with a file called ConsoleHelper.js

const ConsoleHelper = (data) => {
  if (process.env.NODE_ENV === 'production') return;
  console.log(data);
}

export default ConsoleHelper;

So, instead of console.log(data) do ConsoleHelper(data);

undevable
  • 304
  • 1
  • 12
hello world
  • 1,727
  • 6
  • 21
  • 37
  • 1
    So simple yet so effective, no need to even mess with webpack! I added an option to pass a 2nd param since I usually also log out an object of some kind. Thanks so much for posting this! – Spencer Bigum Dec 01 '20 at 20:54
  • @SpencerBigum anytime :) – hello world Dec 02 '20 at 02:04
  • 14
    The problem with this soluition is that the origin for this console msg will be ommitted and replaced with the location of your helper. – Exis Zhang Feb 11 '21 at 01:48
  • @ExisZhang I couldn't understand your comment. could you elaborate? – arunvelsriram Oct 15 '21 at 06:56
  • 3
    @arunvelsriram you lose the original file name and line number of the log, so it's pretty much useless. all your logs will come from ConsoleHelper.js line 3 – orszaczky Jan 11 '22 at 10:50
7

This is my solution using craco.

"@craco/craco": "^6.0.0",
"react-scripts": "4.0.1",

craco.config.js

module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      if (process.env.NODE_ENV === 'production') {
        // remove console in production
        const TerserPlugin = webpackConfig.optimization.minimizer.find((i) => i.constructor.name === 'TerserPlugin');
        if (TerserPlugin) {
          TerserPlugin.options.terserOptions.compress['drop_console'] = true;
        }
      }

      return webpackConfig;
    },
  },
};

weiliang
  • 663
  • 8
  • 13
  • The subject specifically related to the CRA (create-react-app) where you are not able to set the webpack separately. So your solution is not relevant in this case. – Ajay Jun 07 '21 at 17:13
  • 3
    @Ajay craco is a library specifically to allow you to set up webpack when using CRA. The solution is very relevant. – efdee Feb 06 '22 at 15:20
  • @efdee I haven't noticed yours this comment earlier. Thank – Ajay Apr 20 '22 at 17:28
  • is it possible to only drop console.logs? leaving errors and warnings? – benmneb Nov 28 '22 at 05:40
7

This is my solution using craco

install https://babeljs.io/docs/en/babel-plugin-transform-remove-console/

and update craco.config.js like

module.exports = {
  plugins: [{ plugin: require('@semantic-ui-react/craco-less') }],
  babel: {
    // ...
  plugins: process.env.NODE_ENV === "production" ? [["transform-remove-console", { "exclude": ["error"] }]] : []
  }
}
Mudaser Ali
  • 3,989
  • 3
  • 25
  • 27
  • If you use CRACO, you don't need any third-party plugins, as in my previous answer: [link](https://stackoverflow.com/a/67216067/8818057) – weiliang Sep 13 '22 at 02:43
  • @weiliang i had tried that solution but some how it didn't work for me! so then i use this way to fix my issue – Mudaser Ali Sep 14 '22 at 10:12
0

The simple way is to create a new file in root named logger.js

In logger.js

var logger = function logger(...messages){
    if(process.env.NODE_ENV === 'development'){
        console.log(messages);
    }
}
exports.logger = logger;

Now import this logger.js file to your components. For example my component file is demo.jsx

import React from 'react';
var logger = require('../logger.js').logger;

class Demo extends React.Component{
    constructor(props){
    }

    render(){
        return(
            <p>Hello i am demo component</p>
        );
    }

    componentDidMount(){
        logger('I am printing only in developmet')
    }
}
export default Demo;
WapShivam
  • 964
  • 12
  • 20
  • Its fine when start coding. But what will be with already written thousands lines of code. – Ajay Jun 01 '20 at 13:34
  • @Ajay you could simply do a batch rename of all "console.log" to "logger" and then manually go importing it into all your files. I don't really like this approach, I think it adds an easily avoidable import into pretty much all of your files. I think that the answer hello world is the right solution. You could just create a script that changes the drop_console param when you do something like install all your dependencies – Christian Wolf Alves Hess Aug 14 '20 at 15:06
  • this is also useless as you lose the original file and line number reference in the console – orszaczky Jan 11 '22 at 10:52
0

For those not wanting to make changes to their webpack config, this expression does the job as well and without the need of importing a helper function:

process.env.NODE_ENV !== "production" && console.log(data);

For larger or more verbosely logging applications, changing the webpack config is a more elegant solution of course.

For VS Code users i want point out the possibility to set log points and omit the statement altogether if that serves your need.

dnik
  • 1
  • 1
-6

The simple solution to the question is to help others who are facing the same issue.

Ref: https://stackoverflow.com/a/41041580/3574669

The suggestion in the reference, it needs to do a change in the file "webpack.config.js". The create-react-app uses the webpack and the config file internally but it is not possible to add webpack.config.js in my application root for applying the change. This would need to leave the create-react-app setup and build own setup for webpack and configuration. It does not find easy for me after exploring a lot and writing sample code.

Since I am very much satisfied with create-react-app so also don't want to keep aside its benefits.

Finally, I did a simple change in the node_modules/react-scripts/config/webpack.config.js by adding a line drop_console: true, as mentioned in the reference. The suggested code in the reference is as below,

module.exports = {
  optimization: {
    minimizer: [
      new TerserPlugin({
        sourceMap: true, // Must be set to true if using source-maps in production
        terserOptions: {
          compress: {
            drop_console: true, // << this needs only to remove console.log //
          },
        },
      }),
    ],
  },
};

This works fine to me and there is no console log in my production build application by the simple change.

I am using "react-scripts": "3.0.1",

Note: This new line will be cleaned whenever you reinstall "react-scripts" later. So it would need to again do the same change in such an event.

IMPORTANT: Don't use this approach if using CI/CD

Ajay
  • 1,255
  • 1
  • 17
  • 30
  • 16
    How this got 2 upvotes is beyond me. You should never alter code in node_modules as Ajay mentions himself, a simple npm i will just override it, if you want to change the code in one of the repos you're using so much, just fork it and use it locally. – naor.z Apr 22 '20 at 17:27
  • @naor.z I have suggested a single change and a simple precaution. It is easy to implement and maintainable for novice developers as well. Forking and changing are not so simple. Also, this doesn't need any additional effort in making helper as suggested by "hello world" and replace the "console.log" within the entire codes. Please suggest any other solution if simpler than what I have suggested. – Ajay May 25 '20 at 15:45
  • 6
    -1 for really dangerous approach. Simple - yes, wrong - YES. Project with few of these approaches is unmaintainable for any serious work. There are two options: #1 Eject the config #2 Use https://github.com/timarney/react-app-rewired to alter WebPack options I prefer option 2 – zveljkovic Jun 08 '20 at 23:57
  • @zveljkovic The solution is not the best but simple and maintainable for the specific purpose since only one line to maintain. For a very large project and multiple changes in the config, I may agree with your 2 options. But I don't understand why the specific approach for the specific purpose is dangerous since it will not break the code? – Ajay Jun 09 '20 at 06:46
  • People use SO to find answers and they are also used in production/live code. Change of node_module dependencies will not work in CD/CI environments where the `npm i` is used to initialize the deps. #2 above is simple and generally safe. Look at it like this: "You can use the knife as screwdriver but it's not the way to do the job". – zveljkovic Jun 09 '20 at 12:23
  • 1
    Agreed. Will check #2. Thanks – Ajay Jun 09 '20 at 12:32
  • Any change you make to files under node_modules will be lost when running on a machine other than the one where you made the change. This is probably the _worst answer of all_. – efdee Feb 06 '22 at 15:23
  • If the purpose of your answer is to help newbies, then you are doubly wrong. Setting such an example for beginners is either deliberate sabotage or some kind of sloppiness. As has been said several times, this advice is fundamentally problematic because no one ever edits installed dependencies that are derived from package.json. All your changes will be overwritten on subsequent reinstalls and will never end up on any other machine. Fork and install your patched package! – bhoodream Jul 27 '22 at 07:33