你知道Vue3是如何使用Custom Formatters实现chrome个性化日志打印的?

630 阅读1分钟

一、概述

vue3源码中如下代码:

if (__DEV__) {
  initDev()
}

// 实际调用的是
import { initCustomFormatter } from '@vue/runtime-dom'
initCustomFormatter()

在看源码之前先看下效果:

image.png

如果关闭Custom Formatters则打印的效果如下:

image.png

对比以上会发现格式化之后的log日志美观度和结构化清晰很多,那它是如何实现的呢?

二、官方文档以及中文翻译

官方文档

中文翻译

三、源码实现

源码路径packages/runtime-core/src/customFormatter.ts

以下针对ref、reactive、shallowReactive、readOnly、shallowReadonly等数据结构格式化

  const formatter = {
    header(obj: unknown) {
      // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
      if (!isObject(obj)) {
        return null
      }

      if (obj.__isVue) {
        return ['div', vueStyle, `VueInstance`]
      } else if (isRef(obj)) {
        return [
          'div',
          {},
          ['span', vueStyle, genRefFlag(obj)],
          '<',
          formatValue(obj.value),
          `>`
        ]
      } else if (isReactive(obj)) {
        return [
          'div',
          {},
          ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
          '<',
          formatValue(obj),
          `>${isReadonly(obj) ? ` (readonly)` : ``}`
        ]
      } else if (isReadonly(obj)) {
        return [
          'div',
          {},
          ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
          '<',
          formatValue(obj),
          '>'
        ]
      }
      return null
    },
    hasBody(obj: unknown) {
      return obj && (obj as any).__isVue
    },
    body(obj: unknown) {
      if (obj && (obj as any).__isVue) {
        return [
          'div',
          {},
          ...formatInstance((obj as ComponentPublicInstance).$)
        ]
      }
    }
  }

vue、数字、字符串等结构设置样式输出:

  const vueStyle = { style: 'color:#3ba776' }
  const numberStyle = { style: 'color:#0b1bc9' }
  const stringStyle = { style: 'color:#b62e24' }
  const keywordStyle = { style: 'color:#9d288c' }

四、应用

在vue3的开发中,我们开启了Enable custom fromatters之后就可以如期看到格式化之后的log日志。

开启Enable custom fromatters image.png

格式化日志打印效果:

image.png

五、总结

当我们在实际的开发中,也可以针对某些数据结构格式化输出,以提升我们的开发效率。