vue consle.log 只在开发模式下有效 GPT-4 Turbo

vue2生产环境执行console.log不会影响运行效率,不过为了优化生产环境的代码,通常建议移除或替换掉开发阶段的console.log语句。从 GPT-4 Turbo 获得资料并进行测试修改后,可以通过以下方法实现,已经在实际项目中成功运行:

1、注册全局方法 $log_dev_env
在项目 src/main.js 文件中使用 Vue.prototype 注册全局方法,注意遵循一定的命名约定(如前缀`$`)以避免与Vue自身的属性和方法冲突。
下面代码只有在开发模式下process.env.NODE_ENV === 'development'才会执行 console.log 语句,在生产环境中因为NODE_ENV是'production',便不会执行 console.log 语句

1
2
3
4
5
6
// src/main.js
Vue.prototype.$log_dev_env = function (...messages) {
    if (process.env.NODE_ENV === 'development') {
        console.log(...messages);
    }
};

2、引用全局方法 $log_dev_env 分为两种情况
(1)由于 $log_dev_env 是全局方法,在 *.vue 的vue页面或组件中(扩展名为 vue),可以直接使用 this.$log_dev_env 进行引用。比如:

1
2
// 在 *.vue 的vue页面或组件中(扩展名为 vue)
this.$log_dev_env('err' + error) // for debug

(2)在 *.js 文件中(扩展名为 js),this 关键字不会自动指向Vue实例,所以不能直接使用 this.$log_dev_env。而需先 import Vue from "vue"; 再以 Vue.prototype.$log_dev_env 形式引用,否则报错:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '$log_dev_env')

比如:

1
2
3
4
// 在 *.js 文件中(扩展名为 js)
import Vue from "vue";
//...
Vue.prototype.$log_dev_env('reqColumn2List.page', page); // reqColumn2List.page 1

 

posted on   patton88  阅读(25)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示