vue源码分析-1-概述

418 阅读3分钟

源码版本

V2.6.10

整体项目架构

源码目录结构说明

相关技术

flow

主要入口

通过对vue/scripts/config.js(rollup打包配置文件)的分析,web平台相关的主要入口如下

  • vue/src/platforms/web/entry-runtime.js
  • vue/src/platforms/web/entry-runtime-with-compiler.js

主要区别

entry-runtime.js不具备将模板编译为render函数的功能, entry-runtime-with-compiler.js具备将template属性中定义的模板字符串编译为Vue框架内部能识别并执行的render函数

为什么可以不需要模板编译

  1. 因为使用Vue框架可以手写render函数
  2. 使用单文件组件书写Vue组件时,配合webpack+vue-loader可以将模板编译为render函数

以下内容来自官方文档

如果你需要在客户端编译模板 (比如传入一个字符串给 template 选项,或挂载到一个元素上并以其 DOM 内部的 HTML 作为模板),就将需要加上编译器,即完整版:

// 需要编译器
new Vue({
  template: '<div>{{ hi }}</div>'
})

// 不需要编译器
new Vue({
  render (h) {
    return h('div', this.hi)
  }
})

当使用 vue-loader 或 vueify 的时候,*.vue 文件内部的模板会在构建时预编译成 JavaScript。你在最终打好的包里实际上是不需要编译器的,所以只用运行时版本即可。

入口文件定义了什么?

entry-runtime-with-compiler.js

我们通过看vue/src/platforms/web/entry-runtime-with-compiler.js这个文件不难发现,

此入口首先从runtime/index.js目录下引入了export出的Vue对象,先保存了Vue.prototype.$mount(此$mount是由runtime/index.js定义的),

然后覆盖了Vue.prototype.$mount的定义,在覆盖方法中,执行了compileToFunctions函数将template编译为render函数,此函数就是模板编译的重点(后续详细讲解)。

compileToFunctions将模板转化为render函数以后,执行了runtime/index.js中的Vue.$mount方法,并把render函数传给options

/* @flow */
// 引入config文件
import config from '../../core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'
// 引入Vue
import Vue from './runtime/index'
import { query } from './util/index'
import { compileToFunctions } from './compiler/index'
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'

// 返回缓存过了的函数结果
const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})

// 这个其实是runtime中的$mount方法
const mount = Vue.prototype.$mount
// 覆盖了runtime中的$mount方法
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  // 获得element
  el = el && query(el)

  /* istanbul ignore if */
  // 如果el是body,或者是document,报警告
  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
  }

  // 拿到options参数
  const options = this.$options
  // resolve template/el and convert to render function
  // 如果不是render函数
  if (!options.render) {
    // 拿到options.template属性的值
    let template = options.template
    // 如果设置了template属性
    if (template) {
      // 如果是字符串
      if (typeof template === 'string') {
        // 如果第一个字符是#
        if (template.charAt(0) === '#') {
          // 选取到节点
          template = idToTemplate(template)
          /* istanbul ignore if */
          // 选取不到,报警告
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
        // 否则如果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) {
      // 否则去拿到el的子节点
      template = getOuterHTML(el)
    }
    if (template) {
      // 性能埋点
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }

      // 将模板编译为render函数
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        // 改变纯文本插入分隔符 默认是  ["{{", "}}"]  如果改成 ['${', '}']  那么模板上就可以用 ${}去包裹数据了
        delimiters: options.delimiters,
        // 当设为 true 时,将会保留且渲染模板中的 HTML 注释。默认行为是舍弃它们。
        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')
      }
    }
  }
  // 执行runtime中的$mount方法
  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

runtime/index.js

带编译的入口文件引入了runtime/index.js,不带编译模块的入口文件也仅仅是引入了此文件,官方称之为 ==运行时==(用来创建 Vue 实例、渲染并处理虚拟 DOM 等的代码。基本上就是除去编译器的其它一切。)

我们通过分析源码,可得知此文件主要做了如下几件事情

  • 引入core/index中导出的Vue构造函数
  • 给vue的构造函数的config属性添加一些工具方法,即给Vue.config添加方法
  • Vue.options.directives和Vue.options.components赋值默认指令和组件
  • 定义Vue.prototype.$mount方法(此方法主要是将生成的真实dom挂载到dom树,后续讲解)
  • 定义Vue.prototype.__patch__方法(此方法主要是更新真实的dom,后续详细讲解)
/* @flow */

// 引入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 } 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'

// install platform specific utils
// 给config设置了一些方法

// 用来检测一个属性在标签中是否要使用元素对象原生的 prop 进行绑定
Vue.config.mustUseProp = mustUseProp
// 是否是原生标签
Vue.config.isReservedTag = isReservedTag
// 是否是class属性或者style属性
Vue.config.isReservedAttr = isReservedAttr
// 获得标签命名空间,即判断是svg相关标签   还是  math相关标签
Vue.config.getTagNamespace = getTagNamespace
// 是否是未知元素
Vue.config.isUnknownElement = isUnknownElement

// 添加默认指令和组件
// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// install platform patch function
// 挂在patch方法
Vue.prototype.__patch__ = inBrowser ? patch : noop

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

// devtools global hook
/* istanbul ignore next */
// 如果是再浏览器端的话,提示一些信息,让你下载devtools啦,并告诉你这是开发环境

if (inBrowser) {
  setTimeout(() => {
    if (config.devtools) {
      if (devtools) {
        devtools.emit('init', Vue)
      } else if (
        process.env.NODE_ENV !== 'production' &&
        process.env.NODE_ENV !== 'test'
      ) {
        console[console.info ? 'info' : 'log'](
          'Download the Vue Devtools extension for a better development experience:\n' +
          'https://github.com/vuejs/vue-devtools'
        )
      }
    }
    if (process.env.NODE_ENV !== 'production' &&
      process.env.NODE_ENV !== 'test' &&
      config.productionTip !== false &&
      typeof console !== 'undefined'
    ) {
      console[console.info ? 'info' : 'log'](
        `You are running Vue in development mode.\n` +
        `Make sure to turn on production mode when deploying for production.\n` +
        `See more tips at https://vuejs.org/guide/deployment.html`
      )
    }
  }, 0)
}

export default Vue

vue/src/core/index.js

此文件主要做了如下几件事情

  • 从instance/index引入Vue构造函数
  • 初始化Vue相关全局API
  • 定义$isServer,$ssrContext原型属性
  • 定义FunctionalRenderContext原型方法
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'

// 初始化全局api
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

vue/src/core/instance/index.js

  • 此文件主要定义了Vue的构造方法
  • 定义Vue相关的一系列方法如下
// 定义初始化相关方法
initMixin(Vue)
// 定义状态相关方法
stateMixin(Vue)
// 事件相关
// $on$off$once方法
eventsMixin(Vue)
// 生命周期相关
lifecycleMixin(Vue)
// 实现$nextTick 与 _render方法
renderMixin(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'

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)
// 事件相关
// $on$off$once方法
eventsMixin(Vue)
// 生命周期相关
lifecycleMixin(Vue)
// 实现$nextTick 与 _render方法
renderMixin(Vue)

export default Vue

综述

综上我们大致从入口找到了Vue构造函数的定义,那么我们再从Vue构造函数的定义,到Vue相关方法的定义做一个概述如下

image