Daryl Wong
Daryl Wong

Reputation: 2443

NuxtJS: Disable console.log in production env

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

Upvotes: 11

Views: 9099

Answers (2)

nishkaush
nishkaush

Reputation: 1548

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

Upvotes: 3

tony19
tony19

Reputation: 138206

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
        }
      }
    }
  }
}

Upvotes: 25

Related Questions