概述
学一个项目或者插件源码,总是需要找到起始点,从哪里开始打包,又是怎么个运行逻辑。
学习的是 Vue 源码,总要找到 Vue 对象的起始位置。
找起始点大概想法是从打包的 js 逻辑找到 entry 输入。
package.json
"scripts": {
...
"build": "node scripts/build.js",
...
从打包位置开始查,看下 package.json 的 build 命令,起始 js 在 scripts/build.js。
发现内部的 js 的配置在 scripts/config.js 内,看下内部代码。
const builds = {
// Runtime only (CommonJS). Used by bundlers e.g. Webpack & Browserify
'web-runtime-cjs-dev': {
entry: resolve('web/entry-runtime.js'),
dest: resolve('dist/vue.runtime.common.dev.js'),
format: 'cjs',
env: 'development',
banner
...
里面有不同的打包平台的不同配置,拿第一个 runtime 尝试下,看到 entry 指向了 src/platforms/web/entry-runtime.js,这个 js 从 src/platforms/web/runtime/index 中引入了 vue ,只要找到 vue 对象的引用,也就知道了 vue 对象的起始位置 src/core/index。
下面是内部代码。
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)
Object.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 installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
})
Vue.version = '__VERSION__'
export default Vue
从 ./instance/index 中引入了 Vue 对象,看下这里都是什么。
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'
// 使用时要new一个实例的限制,new的同时执行_init
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)
}
// 绑定_init方法
initMixin(Vue)
// 初始化实例状态
stateMixin(Vue)
// 绑定事件方法 $on、$once、$off、$emit
eventsMixin(Vue)
// 初始化_update、_destroy等方法
lifecycleMixin(Vue)
// 初始化一些实例方法
renderMixin(Vue)
export default Vue
从这里看到这就是 Vue 的整个初始化流程了,然后就可以从这里查看具体内部逻辑了。