放弃指南
看了挺多源码分析 打算自己撸一遍源码。
希望加深下理解 也更好的学习。
用于自己以后再阅读理解。
希望自己能在 VUE3.0发布前把这个给鼓捣完。
基础工作
FLOW(类型检查)
项目越复杂就越需要通过工具的手段来保证项目的维护性和增强代码的可读性。 Vue.js 在做 2.0 重构的时候,在 ES2015 的基础上,除了 ESLint 保证代码风格之外,也引入了 Flow 做静态类型检查。之所以选择 Flow,主要是因为 Babel 和 ESLint 都有对应的 Flow 插件以支持语法,可以完全沿用现有的构建配置,非常小成本的改动就可以拥有静态类型检查的能力。
类型推断:通过变量的使用上下文来推断出变量类型,然后根据这些推断来检查类型。/*@flow*/
类型注释:事先注释好我们期待的类型,Flow 会基于这些注释来判断 /*@flow*/ x: string, y: string | number
VUE 源码目录设计
src├── compiler #编译相关├── core #核心代码├── platforms #不同平台的支持├── server #服务端渲染├── sfc # .vue文件解析├── shared #共享代码复制代码
core 目录包含了 Vue.js 的核心代码,包括内置组件、全局 API 封装,Vue 实例化、观察者、虚拟 DOM、工具函数等等。
VUE 源码构建
构建 相对于webpack更轻 只编译js文件 不会对图片等文件的编译(真正写起来感觉上其实差不多)(っ ̯ -。)
VUE 的入口
我们来看一下真正初始化 Vue 的地方,在 src/core/index.js 中:
import Vue from './instance/index'import { initGlobalAPI } from './global-api/index'import { isServerRendering } from 'core/util/env'import { FunctionalRenderContext } from 'core/vdom/create-functional-component'initGlobalAPI(Vue) // 初始化全局 Vue APIObject.defineProperty(Vue.prototype, '$isServer', { get: isServerRendering})Object.defineProperty(Vue.prototype, '$ssrContext', { get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext }})// expose FunctionalRenderContext for ssr runtime helper installationObject.defineProperty(Vue, 'FunctionalRenderContext', { value: FunctionalRenderContext})Vue.version = '__VERSION__'export default Vue在src/core/instance/index.js中import { initMixin } from './init'import { stateMixin } from './state'import { renderMixin } from './render'import { eventsMixin } from './events'import { lifecycleMixin } from './lifecycle'import { warn } from '../util/index'function Vue (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword') } this._init(options)}initMixin(Vue)stateMixin(Vue)eventsMixin(Vue)lifecycleMixin(Vue)renderMixin(Vue)export default Vue复制代码
在这里,我们终于看到了 Vue 的庐山真面目,它实际上就是一个用 Function 实现的类,我们只能通过 new
Vue 去实例化它。
initGlobalAPI
Vue.js 在整个初始化过程中,除了给它的原型 prototype 上扩展方法,还会给 Vue 这个对象本身扩展全局的静态方法,它的定义在 src/core/global-api/index.js 中