【若川视野 x 源码共读】第2期 | vue3 工具函数

304 阅读5分钟

本文参加了由公众号@若川视野 发起的每周源码共读活动,点击了解详情一起参与。

源码

源码地址:github1s.com/vuejs/vue-n…

import { makeMap } from './makeMap'  // 引入

export { makeMap }  // 又导出了。

// 引入一下其他文件变量
export * from './patchFlags'
export * from './shapeFlags'
export * from './slotFlags'
export * from './globalsWhitelist'
export * from './codeframe'
export * from './normalizeProp'
export * from './domTagConfig'
export * from './domAttrConfig'
export * from './escapeHtml'
export * from './looseEqual'
export * from './toDisplayString'
export * from './typeUtils'

// 当前开发环境需要报错,需要dev判断 
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
  ? Object.freeze({})
  : {}
export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []

export const NOOP = () => {}  // 空函数 1. 方便压缩 2.方便判断

/**
 * Always return false.
 */
export const NO = () => false  // 同样因为压缩。

const onRE = /^on[^a-z]/  // 以on开头后面是非a-z的字母
export const isOn = (key: string) => onRE.test(key)  // onClick

// 获取onUpdate:开头的字符串
export const isModelListener = (key: string) => key.startsWith('onUpdate:')

export const extend = Object.assign  // 压缩

export const remove = <T>(arr: T[], el: T) => {  // 删除数组当前索引值
  const i = arr.indexOf(el)
  if (i > -1) {
    arr.splice(i, 1)
  }
}

const hasOwnProperty = Object.prototype.hasOwnProperty  // 压缩
export const hasOwn = ( // 判断是不是自己自身的key
  val: object,
  key: string | symbol
): key is keyof typeof val => hasOwnProperty.call(val, key)

export const isArray = Array.isArray  // 压缩


export const objectToString = Object.prototype.toString  // 压缩
export const toTypeString = (value: unknown): string =>
  objectToString.call(value)  // 获得当前值得类型字符串

export const isMap = (val: unknown): val is Map<any, any> =>
  toTypeString(val) === '[object Map]'  // 判断是否是map
export const isSet = (val: unknown): val is Set<any> =>
  toTypeString(val) === '[object Set]' // 判断是否是set


// toTypeString(val) === '[object Date]'  也可以
export const isDate = (val: unknown): val is Date => val instanceof Date
export const isFunction = (val: unknown): val is Function =>
  typeof val === 'function'
export const isString = (val: unknown): val is string => typeof val === 'string'
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
export const isObject = (val: unknown): val is Record<any, any> =>
  val !== null && typeof val === 'object'

export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}

export const toRawType = (value: unknown): string => {
  // extract "RawType" from strings like "[object RawType]"  // 截取后面的类型
  return toTypeString(value).slice(8, -1)
}

export const isPlainObject = (val: unknown): val is object =>
  toTypeString(val) === '[object Object]'  // 是对象

export const isIntegerKey = (key: unknown) =>
  isString(key) &&
  key !== 'NaN' &&
  key[0] !== '-' &&  // 第0项不是负号
  '' + parseInt(key, 10) === key

/**
 * Make a map and return a function for checking if a key
 * is in that map.
 * IMPORTANT: all calls of this function must be prefixed with
 * /*#__PURE__*/
 * So that rollup can tree-shake them if necessary.
 */
export function makeMap(
  str: string,
  expectsLowerCase?: boolean
): (key: string) => boolean {
  const map: Record<string, boolean> = Object.create(null)  // 创建一个对象
  const list: Array<string> = str.split(',')  // 把字符串按逗号分割
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true  // 放对象里
  }
  // 是不是都小写的。如果不是就返回没有处理小写的。如果是旧返回处理的了,返回的这个函数可以判断,当前map里面有没有val
  return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val]
}

// 用来判断 有没有这些属性
export const isReservedProp = /*#__PURE__*/ makeMap(
  // the leading comma is intentional so empty string "" is also included
  ',key,ref,ref_for,ref_key,' +
    'onVnodeBeforeMount,onVnodeMounted,' +
    'onVnodeBeforeUpdate,onVnodeUpdated,' +
    'onVnodeBeforeUnmount,onVnodeUnmounted'
)

export const isBuiltInDirective = /*#__PURE__*/ makeMap(
  'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo'
)

const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
  const cache: Record<string, string> = Object.create(null)  // 创建缓存对象
  return ((str: string) => {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }) as any
}

const camelizeRE = /-(\w)/g
/**
 * @private
 */
export const camelize = cacheStringFunction((str: string): string => {
  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
})

const hyphenateRE = /\B([A-Z])/g
/**
 * @private
 */
export const hyphenate = cacheStringFunction((str: string) =>
  str.replace(hyphenateRE, '-$1').toLowerCase()
)

/**
 * @private
 */
export const capitalize = cacheStringFunction(
  (str: string) => str.charAt(0).toUpperCase() + str.slice(1)
)

/**
 * @private
 */
export const toHandlerKey = cacheStringFunction((str: string) =>
  str ? `on${capitalize(str)}` : ``
)

// compare whether a value has changed, accounting for NaN.  // 判断两个值是不是相等
export const hasChanged = (value: any, oldValue: any): boolean =>
  !Object.is(value, oldValue)

// 用来执行数组里面的函数。发布订阅 就会把数组都放到一个 对象里面,然后进行遍历,就可以这样做
export const invokeArrayFns = (fns: Function[], arg?: any) => {
  for (let i = 0; i < fns.length; i++) {
    fns[i](arg)
  }
}

// 不可枚举对象的属性
export const def = (obj: object, key: string | symbol, value: any) => {
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: false,
    value
  })
}

// 如果是可以转为 数字 就 转为数字,不可以就返回原来的值
export const toNumber = (val: any): any => {
  const n = parseFloat(val)
  return isNaN(n) ? val : n
}

// 获取当前环境的this
let _globalThis: any
export const getGlobalThis = (): any => {
  return (
    _globalThis ||
    (_globalThis =
      typeof globalThis !== 'undefined'  // globalThis 动态获取当前环境的this。
        ? globalThis
        : typeof self !== 'undefined'  // Web Worker 中可以用self访问this,拿不到window
        ? self
        : typeof window !== 'undefined' // 浏览器
        ? window
        : typeof global !== 'undefined'  // node
        ? global
        : {})  // 其他:小程序之类的
  )
}

总结

1. 引入其他文件变量

export * from './patchFlags'

在项目中把相同类型的内容分到一个文件中,然后通过 * 的方式引入。然后统一从index.js中导出

2. 判断_DEV_

export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
  ? Object.freeze({})
  : {}

判断dev环境,是因为开发环境需要报错信息,但生产环境不需要。所以生产环境是一个{},没有freeze

3. 空函数

 // 使用场景:1. 方便判断 2. 方便压缩
 export const NOOP = () => {}  // 空函数
 // 1. 方便判断,当前定义的就是
 const fn = NOOP
 
 if (fn === NOOP) {// 就可以知道当前初始化的函数还没有发生过变化}
 
 // 2. 方便压缩
 function a() {
 		return () => {} // 当前函数为匿名函数,无法进行压缩
 }
 function a() {
 		return NOOP  // 可以进行变量压缩
 }

4. 删除数组索引值项

export const remove = <T>(arr: T[], el: T) => {  // 删除数组当前索引值 O(n)
  const i = arr.indexOf(el)
  if (i > -1) {
    arr.splice(i, 1)
  }
}

// 比较axios中,没有删除掉数组当前项,只是进行了查找O(1),然后赋值等于null。
// 不会造成数组位移,影响效率。但是感觉还是需要看数组的具体使用场景,不然判断过多,可能得不偿失
// 声明
this.handlers = [];

// 移除
if (this.handlers[id]) {
    this.handlers[id] = null;
}

// 执行
if (h !== null) {
    fn(h);
}

5. 缓存函数处理过的字符串

const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
  const cache: Record<string, string> = Object.create(null)  // 创建缓存对象
  return ((str: string) => {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }) as any
}
// \w -> 0-9a-zA-Z_ 
const camelizeRE = /-(\w)/g
/**
 * @private
 */
export const camelize = cacheStringFunction((str: string): string => {
  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
})
// - 转 驼峰

const hyphenateRE = /\B([A-Z])/g // \B 非单词边界匹配单词
/**
 * @private
 */
export const hyphenate = cacheStringFunction((str: string) =>
  str.replace(hyphenateRE, '-$1').toLowerCase()
)
// 驼峰 转 -

/**
 * @private
 */
// 首字母大写 acc => Acc
export const capitalize = cacheStringFunction(
  (str: string) => str.charAt(0).toUpperCase() + str.slice(1)
)


/**
 * @private
 */
export const toHandlerKey = cacheStringFunction((str: string) =>
  str ? `on${capitalize(str)}` : ``
)
// 转事件 click => onClick

cacheStringFunction 做字符串缓存,防止每一次都进行函数处理。

const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
  const cache: Record<string, string> = Object.create(null)  // 创建缓存对象
  // 第一次执行过后 cache 为 { 'creat-time': 'creatTime' }  
  return ((str: string) => {
    const hit = cache[str]  // 第二次直接从cache对象中取已经处理过的内容
    return hit || (cache[str] = fn(str))
  }) as any
}

const camelizeRE = /-(\w)/g
/**
 * @private
 */
const camelize = cacheStringFunction((str) => {
    console.log(1)  // 只打印一次,第二次的结果,不会在走函数处理函数,而会直接从缓存中取出
    return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
})
console.log(camelize('creat-time'))
console.log(camelize('creat-time'))

6. Object.defineProperty

改写属性对象的描述符

数据描述符(其中属性为:enumerable,configurable,value,writable)与存取描述符(其中属性为enumerable,configurable,set(),get())之间是有互斥关系的。在定义了set()和get()之后,描述符会认为存取操作已被 定义了,其中再定义value和writable会引起错误

let person = {}
Object.defineProperty(person, 'legs', {
    value: 2,
    writable: true,
    configurable: true,
    enumerable: true
});
// 在person中添加legs属性,值为2

7. globalThis

developer.mozilla.org/zh-CN/docs/…

参考文档

juejin.cn/post/699497…