当前位置: 首页 > news >正文

vue中重写并自定义console.log

0. 背景

vue2项目中自定义console.log并输出文件名及行、列号

1. 实现

1.1 自定义console.log

在这里插入图片描述

export default {// 输出等级: 0-no, 1-error, 2-warning, 3-info, 4-debug, 5-loglevel: 5,// 输出模式: 0-default, 1-normal, 2-randommode: 1,// 是否输出图标hasIcon: false,// 是否在vue内使用isVue: true,// 是否打印函数名和所在文件行号isPrintLine: true,// 图标icons: ['🌵', '🎍', '🐾', '🌀', '🐚', '🥝', '🥜', '🥕', '🥒', '🌽', '🍒', '🍅', '🍑', '🍋', '🍈', '🌶', '🌰', '🍠', '🍆', '🍄', '🍐', '🍌', '🍍', '🍇', '🍏', '🍓', '🍎', '🍊', '🐴', '🐗', '🦄', '🐑', '🐶', '🐔', '🐼', '🐒', '🌝', '💄', '💋', '👠', '👗', '👙', '🧣', '🍰', '🍭', '🍳', '🎄', '🎱', '⚽', '🏀', '🎵', '🚄', '⭕', '❌', '❓', '❗', '💯'],// 标准颜色colors: {error: '#f7630c',warning: '#ca5010',info: '#0078d7',debug: '#13a10e',log: '#1f1f1f'},// 获取随机图标randomIcon: function () {return this.icons[Math.floor(Math.random() * this.icons.length)]},// 获取随机颜色randomColor: function () {const r = Math.floor(Math.random() * 256)const g = Math.floor(Math.random() * 256)const b = Math.floor(Math.random() * 256)// 返回随机生成的颜色return `rgb(${r}, ${g}, ${b})`},// 默认打印printDefault: function (tag, args) {console.log(tag, ...args)},// 标准打印printNormal: function (tag, args) {console.log(`%c ${tag} : `, `color: ${this.colors[tag]}`, ...args)},// 随机打印printRandom: function (tag, args) {const icon = this.randomIcon()const bgColor = this.randomColor()const color = this.randomColor()console.log(`%c ${icon}`, `font-size:20px;background-color: ${bgColor};color: ${color};`, tag + ' : ', ...args)},print: function (tag, args) {if (this.isPrintLine) {if (!this.isVue) {// 获取函数名和行号const err = new Error()// console.log(err.stack)const stack = err.stack.split('\n').slice(3).map(line => line.trim())// console.log(stack)const caller = stack[0].match(/at (.+) \(/) ? stack[0].match(/at (.+) \(/)[1] : stack[0].match(/at (.+):\d+:/)[1]const fileLine = stack[0].match(/\(.*\/(.+)\)/) ? stack[0].match(/\(.*\/(.+)\)/)[1] : stack[0].match(/(\d+:\d+)/)[1]// console.log(`${caller} (${fileLine}):\n`)args.shift(`[${caller} (${fileLine})]\n`)} else {args.shift()}} else {if (this.isVue) {args.shift().shift()}}switch (this.mode) {case 0: {this.printDefault(tag, args)break}case 1: {this.printNormal(tag, args)break}case 2: {this.printRandom(tag, args)break}}},error: (function (oriLogFunc) {return function (...args) {const tag = 'error'if (this.level >= 1) {// oriLogFunc.call(console, 'error : ', args)this.print(tag, args)}}})(console.log),warning: (function (oriLogFunc) {return function (...args) {const tag = 'warning'if (this.level >= 2) {// oriLogFunc.call(console, 'warning : ', args)this.print(tag, args)}}})(console.log),info: (function (oriLogFunc) {return function (...args) {const tag = 'info'if (this.level >= 3) {// oriLogFunc.call(console, 'info : ', args)this.print(tag, args)}}})(console.log),debug: (function (oriLogFunc) {return function (...args) {const tag = 'debug'if (this.level >= 4) {// oriLogFunc.call(console, 'debug : ', ...args)this.print(tag, args)}}})(console.log),log: (function (oriLogFunc) {return function (...args) {const tag = 'log'if (this.level >= 5) {// oriLogFunc.call(console, 'log : ', ...args)this.print(tag, args)}}})(console.log)
}

1.2 webpack记录行号

添加自定义loader

在这里插入图片描述

module.exports = function (content) {content = content.toString('utf-8')if (this.cacheable) this.cacheable()const { name = ['this.\\$iceLog.log'] } = this.query.config || {}const fileName = this.resourcePath.replaceAll('\\', '/').match(/(?<=\/)(src.*)/gm)[0]content = content.split('\n').map((line, row) => {let loggerName = name[0]for (let i = 1; i < name.length; i++) {loggerName += '|' + name[i]}const re = new RegExp(`(${loggerName})\\((.*?)\\)`, 'g')let resultlet newLine = ''let cursor = 0while ((result = re.exec(line))) {const col = result.indexnewLine += line.slice(cursor, result.index) + `${result[1]}('[${fileName}:${row + 1}:${col + 1}]\\n', ` + result[2] + ')'cursor += col + result[0].length}newLine += line.slice(cursor)return newLine}).join('\n')return content
}
module.exports.raw = true

1.3 配置loader

修改vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,lintOnSave: false,chainWebpack: config => {// config.devtool('eval-cheap-module-source-map')config.module.rule('vue').use('vue-loader').end().rule('log-lineno').use('./loaders/log-lineno.loader').loader('./loaders/log-lineno.loader').options({config: {name: ['this.\\$iceLog.error','this.\\$iceLog.warning','this.\\$iceLog.info','this.\\$iceLog.debug','this.\\$iceLog.log']}}).end()}
})

2. 测试

  created () {this.$iceLog.log(123)this.$iceLog.error(1, 2, 3, 4)},

在这里插入图片描述

3. 问题

3.1 .vue文件被编译多次,自定义log会输出两个目录

在这里插入图片描述
解决:
在自定义函数中移除一个参数:

在这里插入图片描述

x. 参考

  1. 重写并自定义console.log()输出样式
  2. 巧用 webpack 在日志中记录文件行号
  3. vue webpace相关
  4. Vue2工程化 webpack配置 loader插件
  5. webpack初学者看这篇就够了
  6. 你了解webpack中配置的loader的执行顺序吗?
http://www.lryc.cn/news/93337.html

相关文章:

  • 基于OpenCV 和 Dlib 进行头部姿态估计
  • 24个Jvm面试题总结及答案
  • freemarker 生成前端文件
  • Pycharm+pytest+allure打造高逼格的测试报告
  • Mybatis-Plus中update更新操作用法
  • 16道JVM面试题
  • HttpRunner 接口自动化测试框架实战,打造高效测试流程
  • 手写一个webpack插件(plugin)
  • jvm常见面试题
  • TF-A 项目的长期支持介绍
  • 企业电子招标采购系统源码java 版本 Spring Cloud + Spring Boot
  • 7.Mysql 事务底层
  • 15.DIY可视化-拖拽设计1天搞定主流小程序-分类联动文章列表实时刷新
  • 【SpringCloud】二、服务注册发现Eureka与负载均衡Ribbon
  • 图形学实验(完整文件见上传)
  • Spark大数据处理学习笔记(3.2.1)掌握RDD算子
  • lammps初级:石墨烯、金属材料、纳米流体、热传导、多成分体系、金属、半导体材料的辐照、自建分子力场、MOFS、H2/CO2混合气体等模拟
  • 【MarkerDown】CSDN Markdown之时序图sequenceDiagram详解
  • ReentrantLock实现原理-公平锁
  • 掌握Scala数据结构(2)MAP、TUPLE、SET
  • flutter:文件系统目录、文件读写
  • 计算机提示“找不到vcruntime140.dll,无法继续执行代码可”以这样子修复
  • 深度学习pytorch实战五:基于ResNet34迁移学习的方法图像分类篇自建花数据集图像分类(5类)超详细代码
  • Rust in Action笔记 第五章 深入理解数据
  • Cocos creator实现飞机大战空中大战《战击长空》小游戏资源及代码
  • 2.4 逻辑代数的基本定理
  • 适用于 Linux 的 Windows 子系统wsl文档
  • C++特殊类的设计与类型转换
  • 如何通过关键词搜索API接口
  • 智驾域控新战争打响,谁在抢跑?