简体   繁体   English

NuxtJS:在生产环境中禁用 console.log

[英]NuxtJS: Disable console.log in production env

I am looking for a way to disable console.log() for production env.我正在寻找一种为生产环境禁用console.log()的方法。 Something like putting the below code to nuxt.config.js or index.js :类似于将以下代码nuxt.config.jsindex.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我的 nuxt.config.js 在这里https://gist.github.com/somaria/9a2b0e06497d13a35fe9eee141a15d07

Nuxt's build process includes terser , which can be configured to automatically remove console statements from your production build. Nuxt 的构建过程包括terser ,它可以配置为自动从生产构建中删除控制台语句。 You could set build.terser.terserOptions :您可以设置build.terser.terserOptions

// nuxt.config.js
export default {
  build: {
    terser: {
      // https://github.com/terser/terser#compress-options
      terserOptions: {
        compress: {
          drop_console: true
        }
      }
    }
  }
}

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的文件,如下所示:

// 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里面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.这将在实例化根 Vue.js 应用程序之前运行。

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还有其他的东西,你可以配置它运行客户端或服务器端等。更多信息在这里 - https://nuxtjs.org/guide/plugins#vue-plugins

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM