Vue源码解析

一、源码目录

 

 二、dist目录

 

输出格式说明:

带有common的文件是为browserify、webpack1准备的,

带有vue.esm的文件是为webpack2+准备的,

带有common的文件是兼容带有common的文件和AMD的(可在node端和浏览器里用)

带有runtime的文件仅包含运行时,无编译器

 

三、测试环境

1.安装依赖:

cnpm i 

2.全局安装打包工具rollup:

cnpm i --save rollup -g

3.给package.json中的scripts.dev命令加上--sourcemap,方便调试查看源码

4.执行dev命令,若没报错则vue运行成功,dist目录会多出vue.js.map的映射文件

npm run dev

5.在examples创建测试文件tset/test.html引入vue.js:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div id="app"></div>
    <script src="../../dist/vue.js"></script>
    <script>
        new Vue({
            el:'#app'
        })
    </script>

</body>
</html>

当source中能看到src时 说明sourcemap生效

 

四、探寻入口文件

1.根据package.json文件中的scripts.dev:

应从scripts/config.js中着找到目标web-full-dev

根据入口文件地址是resolve('web/entry-runtime-with-compiler.js'),查找resolve()

alias.js:

拼接出的入口文件地址是:src/platforms/web/entry-runtime-with-compiler.js

 

2.入口文件的作用:(src/platforms/web/entry-runtime-with-compiler.js

扩展$mount():处理开发者写入的template/el属性,尝试编译为render方法

/* @flow */

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 { compileToFunctions } from './compiler/index'
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'

const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})

/**
 * 扩展Vue.prototype.$mount方法:
*/
// 将原本的$mount保存起来,等待后面调用
const mount = Vue.prototype.$mount
// 重写$mount
Vue.prototype.$mount = function (
  // flow代码:进行类型设置
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)

  /* istanbul ignore if */
  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
  }

  /**
   * 处理传进来的el和template属性:
   * 如果写了render,则使用render为模板,否则
   * 如果写了template(选择器或节点),则使用template为模板,否则
   * 查找el中的选择器为模板
   * */ 
  const options = this.$options
  // 如果开发者没有写render方法
  if (!options.render) {
    let template = options.template
    if (template) { // 如果开发者写了template
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') { // 当template为选择器时
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {  // 当template为节点时
        template = template.innerHTML
      } else { //  // 当template不为选择器和节点时报警
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }

    // 将template模板编译成render方法
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }

      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        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

 

五、初始化流程分析

1.根据入口文件中:

import Vue from './runtime/index'

找到Vue在 vue\src\platforms\web\runtime\index.js 中,这个文件定义了$mount和__patch__

// 定义$mount(),执行挂载mountComponent(this, el, hydrating)
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}
// 定义__patch__
Vue.prototype.__patch__ = inBrowser ? patch : noop

这个文件中的vue是在另一个文件(vue\src\core\index.js)引入的:

import Vue from 'core/index'

 

2.vue\src\core\index.js 文件主要是定义全局api:

// 定义全局api
initGlobalAPI(Vue)
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
initUse(Vue)
initMixin(Vue)
initExtend(Vue)
initAssetRegisters(Vue)

这个文件中的vue是在另一个文件(vue\src\core\instance\index.js)引入的:

import Vue from './instance/index'

 

3.vue\src\core\instance\index.js 文件主要是定义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'

// 定义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)
}

initMixin(Vue) // 实现了_init()
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

4.vue\src\core\instance\init.js 中的 _init() : 主要进行初始化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值