源码地址
https://github.com/vuejs/vue-next
环境准备
1. 查看 Vuejs 贡献指南
https://github.com/vuejs/vue-next/blob/master/.github/contributing.md
使用的是 pnpm(不是本期重点,可查看附录链接,查看使用原因):https://pnpm.io/
2. 生成 sourcemap 代码版本
npm run dev --sourcemap
3. 例子引用
执行后生成 vue.global.js,因此可以直接构造 html 例子引入即可定位查看源码:
created packages/vue/dist/vue.global.js in 2.3s
<html>
<body>
<div id="counter">{{ counter }}</div>
<script src="../packages/vue/dist/vue.global.js"></script>
<script>
const Counter = {
data() {
return {
counter: 12321321
}
}
}
Vue.createApp(Counter).mount('#counter')
</script>
</body>
</html>
工具函数
1. 常量赋值
一般使用在默认值赋值上:
// 空 object
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
? Object.freeze({})
: {}
// 空 array
export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
// 空 function
export const NOOP = () => {}
// 永远只会返回 false 的函数
/**
* Always return false.
*/
export const NO = () => false
开发环境(DEV = true)时,EMPTY_OBJ 和 EMPTY_ARR 都使用 Object.freeze,避免在开发过程中修改到该引用类型值(https://github.com/vuejs/vue-next/commit/edd49dcab40eb3faa44248772b176d5eebfd30fe)
2. 类型判断
// 判断是不是 数组
export const isArray = Array.isArray
// 判断是不是 Map
export const isMap = (val: unknown): val is Map<any, any> =>
toTypeString(val) === '[object Map]'
// 判断是不是 Set
export const isSet = (val: unknown): val is Set<any> =>
toTypeString(val) === '[object Set]'
// 判断是不是 日期
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'
// 判断是不是 Symbol
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
// 判断是不是 Object
export const isObject = (val: unknown): val is Record<any, any> =>
val !== null && typeof val === 'object'
// 判断是不是 Promise
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
附录
- 为什么使用 pnpm:https://zhuanlan.zhihu.com/p/352437367
- pnpm 使用符号链接创建 node_modules 结构:https://pnpm.io/zh/symlinked-node-modules-structure
- pnpm 严格性有助于避免愚蠢错误:https://www.kochan.io/nodejs/pnpms-strictness-helps-to-avoid-silly-bugs.html