11

I am looking for a way to disable console.log() for production env. Something like putting the below code to nuxt.config.js or index.js:

if (process.env.NODE_ENV !== "development") {
  console.log = () => {};
}

I tried it, but it doesn't work. Any help would be appreciated.

My nuxt.config.js is here https://gist.github.com/somaria/9a2b0e06497d13a35fe9eee141a15d07

tony19
  • 125,647
  • 18
  • 229
  • 307
Daryl Wong
  • 2,023
  • 5
  • 28
  • 61
  • You could try using `NUXT_ENV_` before your variable names during the build phase. Can you also share your nuxt.config.js file? – nishkaush Oct 18 '20 at 03:32

2 Answers2

22

Nuxt's build process includes terser, which can be configured to automatically remove console statements from your production build. You could set build.terser.terserOptions:

// nuxt.config.js
export default {
  build: {
    terser: {
      // https://github.com/terser/terser#compress-options
      terserOptions: {
        compress: {
          drop_console: true
        }
      }
    }
  }
}
tony19
  • 125,647
  • 18
  • 229
  • 307
3

As an alternative, this can also be done with Plugins.

Under Plugins folder, we can create a file called disableLogs.js which can look like so:

// plugins/disableLogs.js

export function disableLogs() {
  console.log = () => {};
  // or you can override any other stuff you want
}

process.env.NODE_ENV === "production" ? disableLogs() : null;

Then we can register this plugin to be used inside nuxt.config.js

// nuxt.config.js
plugins: [
  { src: "~/plugins/disableLogs.js" },
  { src: "~/plugins/any-other-plugin.js"
],

This will run before instantiating the root Vue.js Application.

There are other things where you can configure it to run either client or server side, etc. More info here - https://nuxtjs.org/guide/plugins#vue-plugins

nishkaush
  • 1,512
  • 1
  • 13
  • 20