Use Grunt to remove console.logs from your code

You already know that it's a good practice to remove the console.log statements from your code when deploying to production.
So you manually go over the code that you recently changed to remove any console.logs before uploading the files to the server.

This is however a task that is perfect for automating and this is where tools like Grunt or Gulp come in.

If you don't already have Grunt installed, go ahead and do that first as I've explained in a previous blog post.

Now, the process we aim to achieve is:

  1. copy all the source files into a "dist" folder, where we will have the cleaned up code
  2. run the cleanup grunt task in place in the dist folder

For this, let's install two gulp tasks, grunt-contrib-copy and grunt-remove-logging:

$ npm install --save-dev grunt-contrib-copy grunt-remove-logging

Then, let's set them up in your Gruntfile.js:

module.exports = function(grunt) {
  // Project configuration
  grunt.initConfig({
    // Configure grunt-contrib-copy
    copy: {
      main: {
        // Allow creating the list of files dinamically (http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically)
        expand: true,
        // Execute the command from inside the /src folder
        cwd: 'src',
        // Also copy subfolders        
        src: '**',
        // Put the final files inside /dist
        dest: 'dist/',
      },
    },
    // Configure grunt-remove-logging
    removelogging: {
      dist: {
        // Clean up all js file inside "dist" or its subfolders
        src: "dist/**/*.js",
      }
    }
  });

  // Load the plugins
  grunt.loadNpmTasks("grunt-contrib-copy");
  grunt.loadNpmTasks("grunt-remove-logging");
 
  // Default task(s) 
  grunt.registerTask('default', ['copy', 'removelogging']);
}

Finally, run the grunt task from your project root folder:

$ grunt
Running "copy:main" (copy) task
Copied 1 file

Running "removelogging:dist" (removelogging) task
Removed 1 logging statements from dist/index.js

Done.

That's it! Now upload to production the file in the dist folder and you're done!