- Published on
How to Disable Console Logs in Vanilla JavaScript in Production
- Authors

- Name
- nikUnique

The Problem
There is a standard situation when you develop a regular JavaScript app: you use console logs here and there, but during production, you do not need them there at all.
The Solution
Here is the code of a function and the function call, and in here we check for localhost and the localhost IP address. If the hostname doesn't include any of these, then we consider it to be a production environment, so we override some of the console logging methods.
function disableLogging() {
if (
!location.hostname.includes("localhost") &&
!location.hostname.includes("127.0.0.1")
) {
["log", "info", "debug", "table", "dir", "trace"].forEach((method) => {
console[method] = () => {};
});
// console.warn() and console.error() still works, so that you do not miss them in production
}
}
disableLogging();
You can just put it in a separate file, and then import it into your main entry point. Place the import at the top of the file to ensure that it runs before other code. I, for example, placed it in the controller.js file, which is the file where everything begins, where I import all other parts of the program.
Here you go, this is how you can get rid of console logs in production in a regular JS app.
Got questions? Send me an email to commitnobug@outlook.com