vue源碼分析系列之入口文件分析

入口尋找

  1. 入口platforms/web/entry-runtime-with-compiler中import了./runtime/index導出的vue。
  2. ./runtime/index中引入了core/index中的vue.
  3. core/index中引入了instance/index中的vue
  4. instance/index中,定義了vue的構造函數

instance/index中的vue

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)
// 原型上掛載$data的屬性描述符getter,返回this._data
// 原型上掛載$props的屬性描述符getter, 返回this._props
// 原型上掛載$set與$delete方法,用來爲對象新增/刪除響應式屬性
// 原型上掛載$watch方法
stateMixin(Vue)
// 原型上掛載事件相關的方法, $on、$once、$off、$emit。
eventsMixin(Vue)
// 原型上掛載_update、$destroy與$forceUpdate方法,與組件更新有關。
lifecycleMixin(Vue)
// 原型掛載組件渲染相關方法,_render方法(用來返回vnode,即虛擬dom)
renderMixin(Vue)

export default Vue

core/index中的vue

index

import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'

// 初始化一些全局API
initGlobalAPI(Vue)

// 是否是服務端渲染
Object.defineProperty(Vue.prototype, '$isServer', {
  get: isServerRendering // global['process'].env.VUE_ENV === 'server'
})

// ssr相關
Object.defineProperty(Vue.prototype, '$ssrContext', {
  get () {
    /* istanbul ignore next */
    return this.$vnode && this.$vnode.ssrContext
  }
})

Vue.version = '__VERSION__'

export default Vue

initGlobalAPI

  // 定義vue配置對象,配置對象詳情見 import config from '../config'中的備註
  const configDef = {}
  configDef.get = () => config
  Object.defineProperty(Vue, 'config', configDef)

  // 定義一些內部公用方法
  Vue.util = {
    warn, // ⚠️警告打印相關
    extend, // 淺拷貝函數
    mergeOptions, // 配置合併,用到的時候細看
    defineReactive // 定義響應式屬性的方法。
  }

  // 靜態方法,同$set、$delete、$nextTick
  Vue.set = set
  Vue.delete = del
  Vue.nextTick = nextTick

  Vue.options = Object.create(null)
  ASSET_TYPES.forEach(type => {
    Vue.options[type + 's'] = Object.create(null)
  })
  // Vue.options => {"components":{},"directives":{},"filters":{}}

  // 跟Weex's multi-instance scenarios多場景有關
  Vue.options._base = Vue;

  //將內置組件塞進來
  extend(Vue.options.components, builtInComponents)

  // 定義Vue.use,主要在應用在插件系統中
  initUse(Vue)
  // 定義Vue.mixin, 就一句this.options = mergeOptions(this.options, mixin)
  initMixin(Vue)
  // 定義Vue.extend, 用作原型繼承,通過它,可以創建子組件的構造函數
  initExtend(Vue)
  // 擴展Vue.component,Vue.directive,Vue.filter方法
  initAssetRegisters(Vue)

runtime/index中的vue

import Vue from 'core/index'
import config from 'core/config'
import { extend, noop } from 'shared/util'
import { mountComponent } from 'core/instance/lifecycle'
import { devtools, inBrowser, isChrome } from 'core/util/index'

import {
  query,
  mustUseProp,
  isReservedTag,
  isReservedAttr,
  getTagNamespace,
  isUnknownElement
} from 'web/util/index'

import { patch } from './patch'
import platformDirectives from './directives/index'
import platformComponents from './components/index'

// 一些標籤檢查類的方法。平臺相關
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement

// 平臺相關指令組件
// 指令有model與show
// 組件有Transition與TransitionGroup
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop

// public mount method
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

entry-runtime-with-compiler中的vue

import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'

import Vue from './runtime/index'
import { query } from './util/index'
import { shouldDecodeNewlines } from './util/compat'
import { compileToFunctions } from './compiler/index'

// 根據id返回dom內容
const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})

// 重寫$mount方法
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)

  /* 將vue綁定到body或者html元素上的錯誤提示 */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // 解析template或者el屬性,將其轉化爲render函數
  if (!options.render) {
    let template = options.template
    // 獲得模板字符串
    if (template) {
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }
    // 獲得模板字符串後,編譯模板爲render函數
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }

      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  return mount.call(this, el, hydrating)
}

/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
function getOuterHTML (el: Element): string {
  if (el.outerHTML) {
    return el.outerHTML
  } else {
    const container = document.createElement('div')
    container.appendChild(el.cloneNode(true))
    return container.innerHTML
  }
}

Vue.compile = compileToFunctions

export default Vue
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章