前言
- 本文参加了由公众号@若川视野 发起的每周源码共读活动,点击了解详情一起参与。
- 这是源码共读的第2期,链接:第2期 | vue3 工具函数
学习目标
本文分析vue-next的shared模块的工具函数
源码地址:shared/src/index.ts
源码分析
源码中 DEV 编译后是环境判断 process.env.NODE_ENV !== 'production'
babel解析默认配置
export const babelParserDefaultPlugins = [
'bigInt',
'optionalChaining',
'nullishCoalescingOperator'
] as const
babel 解析默认配置,这里使用了 const 断言(as const)如果没有的话 babelParserDefaultPlugins 会被推断成 string[]
bigInt 是一种内置对象,它提供了一种方法来表示大于 2^53 - 1 的整数
optionalChaining 可选链操作符(?.)
nullishCoalescingOperator 空值合并运算符(??)
EMPTY_OBJ 空对象
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__ ? Object.freeze({}) : {}
EMPTY_ARR 空数组
export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
NOOP 空函数
export const NOOP = () => {}
NO 返回 false 的函数
export const NO = () => false
isOn 是否on开头
const onRE = /^on[^a-z]/
export const isOn = (key: string) => onRE.test(key)
isModelListener 是否 Model 事件
export const isModelListener = (key: string) => key.startsWith('onUpdate:')
extend 合并
export const extend = Object.assign
remove 删除数组某项
export const remove = <T>(arr: T[], el: T) => {
const i = arr.indexOf(el)
if (i > -1) {
arr.splice(i, 1)
}
}
hasOwn 是否存在某属性
const hasOwnProperty = Object.prototype.hasOwnProperty
export const hasOwn = (
val: object,
key: string | symbol
): key is keyof typeof val => hasOwnProperty.call(val, key)
toTypeString 对象转换为字符串
export const objectToString = Object.prototype.toString
export const toTypeString = (value: unknown): string => objectToString.call(value)
isArray 是否是数组
export const isArray = Array.isArray
isMap 是否是Map
export const isMap = (val: unknown): val is Map<any, any> => toTypeString(val) === '[object Map]'
isSet 是否是Set
export const isSet = (val: unknown): val is Set<any> => toTypeString(val) === '[object Set]'
isDate 是否是日期
export const isDate = (val: unknown): val is Date => val instanceof Date
isFunction 是否是函数
export const isFunction = (val: unknown): val is Function => typeof val === 'function'
isString 是否是字符串
export const isString = (val: unknown): val is string => typeof val === 'string'
isSymbol 是否是symbol
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
isObject 是否是纯对象
export const isObject = (val: unknown): val is Record<any, any> => val !== null && typeof val === 'object'
isPromise 是否是promise
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
toRawType 类型截取
export const toRawType = (value: unknown): string => {
// extract "RawType" from strings like "[object RawType]"
return toTypeString(value).slice(8, -1)
}
isPlainObject 是否是纯字符串
export const isPlainObject = (val: unknown): val is object => toTypeString(val) === '[object Object]'
isIntegerKey 是不是数字类型
export const isIntegerKey = (key: unknown) => isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key
isReservedProp 是否为保留字段
export const isReservedProp = /*#__PURE__*/ makeMap(
// the leading comma is intentional so empty string "" is also included
',key,ref,' +
'onVnodeBeforeMount,onVnodeMounted,' +
'onVnodeBeforeUpdate,onVnodeUpdated,' +
'onVnodeBeforeUnmount,onVnodeUnmounted'
)
makeMap 根据逗号分隔的字符串生成Map映射,这里是生成vue的一些内置属性和生命周期Map映射
cacheStringFunction 函数缓存
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
}
下文的字母大小写转换使用该函数,缓存可以减少相同正则匹配等操作
camelize 连字符转驼峰
const camelizeRE = /-(\w)/g
export const camelize = cacheStringFunction((str: string): string => {
return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
})
如:on-click => onClick
hyphenate 大写转小写
// \B 是指 非 \b 单词边界。
const hyphenateRE = /\B([A-Z])/g
export const hyphenate = cacheStringFunction((str: string) =>
str.replace(hyphenateRE, '-$1').toLowerCase()
)
capitalize 首字母大写
export const capitalize = cacheStringFunction(
(str: string) => str.charAt(0).toUpperCase() + str.slice(1)
)
toHandlerKey 首字母大写后前面加on
export const toHandlerKey = cacheStringFunction((str: string) => str ? `on${capitalize(str)}` : ``)
hasChanged 是否有变化
export const hasChanged = (value: any, oldValue: any): boolean => !Object.is(value, oldValue)
Object.is() 方法判断两个值是否为同一个值。如果满足以下条件则两个值相等
invokeArrayFns 执行函数
export const invokeArrayFns = (fns: Function[], arg?: any) => {
for (let i = 0; i < fns.length; i++) {
fns[i](arg)
}
}
def 对象属性代理
export const def = (obj: object, key: string | symbol, value: any) => {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: false,
value
})
}
toNumber 转数字
export const toNumber = (val: any): any => {
const n = parseFloat(val)
return isNaN(n) ? val : n
}
getGlobalThis 全局对象
let _globalThis: any
export const getGlobalThis = (): any => {
return (
_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {})
)
}
总结
基于ts的各种工具函数封装,对于ts初学者来讲也是不错的借鉴。