How to automatically remove console.logs() in development?

Viewed 3746

The Problem

Trying to lint an old React application that has 30+ console.logs() throughout the code base. I setup a linter and code formatter, ESLint and Prettier respectively.

This setup works great and it shows me where the console.logs() are in the source. But, the --fix flag for ESLint does not remove the logs. Is there any way to automatically remove console.logs()? I've seen articles on how to do this via webpack to prevent the logs from going into production, however, I would like to remove these earlier in a pre-commit or pre-push hook for instance.

What I've Tried

I tried setting up a script using gulp-strip-debug. It fails with an assertion error. When I changed the src path from './src/**.js' to './**.js' I do not get the assertion error but nothing happens.

Learned about this from Jun711 blog. The "How to remove console log from your JavaScript files programmatically?" blog post.

Gulpfile

gulpfile.js: root of project directory

const gulp = require('gulp');
const stripDebug = require('gulp-strip-debug');
gulp.task(
  'strip-debug',
  () =>
    gulp
      .src('./src/**.js') // input file path
      .pipe(stripDebug()) // execute gulp-strip-debug
      .pipe(gulp.dest('./')) // output file path
);

Package.json

{
  "name": "end-the-pandemic",
  "version": "1.0.0",
  "dependencies": {
    "shelter-in-place": "11.5.20",
    "stay-home": "11.5.21",
    "who-is-still-voting-for-trump": "11.3.20", 
    "seriously-why": "2.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "lint": "eslint '*/**/*.js' --quiet --fix",
    "clean": "gulp strip-debug",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
  },
...

Terminal

yarn clean

Output

AssertionError [ERR_ASSERTION]: Task function must be specified

Obviously, I could have done a search and deleted most of them manually with the time I spent writing this question but for future reference, is there anyway to do this with a command? I would like to put yarn clean in a pre-commit hook if possible.

1 Answers

You could make this trick it would be good in this case

if (env === 'production') {
    console.log = function () {};
}

this will overwrite the real log function into an empty one

make sure you add it at the top of your react app

Another solution

there is a package called babel-plugin-transform-remove-console could help you after installing it from npm

npm install babel-plugin-transform-remove-console

after installing create a .babelrc file in your project root dir and add this line to it

{
  "plugins": ["transform-remove-console"]
}
Related