Babel Plugin To Remove Console Logs In Production

Babel Plugin To Remove Console Logs In Production

I have faced the problem of having to remove javascript console logs manually in production. I want to have those logs during development, but not in production. There are two ways to achieve this., a messy way would be to comment out the console logs every time I deploy to production, and another way is to write a custom wrapper function around console so that it prints out logs only in development.

I did not like both of these solutions. The first one is very time-consuming. The second one does not feel natural to use. I don't want to change anything in my dev workflow. So I dug around and found a nice and easy way to hide logs in production but still show them in development. In this blog post, I will show you what it us and how you can set it up for your projects.

I found a babel plugin called babel-plugin-transform-remove-console which does exactly what I needed.

Since it's a babel plugin, it is so easy to install and use it in any of the projects that were configured with webpack or babel.

For example, I have a very basic next.js project setup with babel. I will add this plugin to that project.

My initial .babelrc file looks like follows:

{
  "presets": ["next/babel"],
}

First, install the plugin.

npm install babel-plugin-transform-remove-console --save-dev

Now, in your .babelrc file, add this plugin to production env.

{
  "presets": ["next/babel"],
  "env": {
    "production": {
      "plugins": ["transform-remove-console"]
    }
  }
}

That's it. Now, console.log's in your project will not be shown in production while they will still be shown during development.

Like I said at the start of the post, there are other ways to achieve this, there are many console wrappers available which does the same job, but they don't feel natural for me to use them. This plugin is very straightforward and does its job perfectly without me changing anything in my dev workflow. Do give this a try and tell me if you like it.

All the code that is written in this article is available on my github at pbteja1998/nextjs-no-console-logs-in-prod

If you have any feedback or suggestions to improve the blog post, please leave them in the comments. I will try to improve the post accordingly.

If this blog post was helpful to you, please consider liking it and sharing it so that it reaches more people.

If you want to get notified as soon as I write a new blog post, you can click on Subscribe button at the top of this page. You can also follow me here at Bhanu Teja P or on twitter at @pbteja1998 to get updated.

Links and References

Did you find this article valuable?

Support Bhanu Teja Pachipulusu by becoming a sponsor. Any amount is appreciated!

ย