Vue源码学习笔记1:整体过一下,找到各个模块的入口

学习Vue源码文件太多,不知道从哪里看?我来整理了一下,把入口文件拎出来,希望对萌新们有帮助

先下载,装一下依赖
Vue源码下载: https://github.com/vuejs/vue.git
npm install 安装依赖

然后开始找入口了
打开package.josn文件,找到dev

"dev": "rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-full-dev",

–sourcemap是我自己加上去的哦,方便调试,你们也可以加一下

在package.josn文件中,根据dev的内容,可以知道我们需要打开scripts/config.js文件,寻找web-full-dev的内容

	// Runtime+compiler development build (Browser)
 	'web-full-dev': {
	 	entry: resolve('web/entry-runtime-with-compiler.js'),
		dest: resolve('dist/vue.js'),
		format: 'umd',
		env: 'development',
		alias: { he: './entity-decoder' },
		banner
	 },

从这可知入口文件是web/entry-runtime-with-compiler.js,打开src/platforms/web/entry-runtime-with-compiler.js
来看一下在这里做了些啥,我的分析为中文注释

	/* @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' // 看到了vue,可能是vue的构造方法,看完这个文件后就去这里
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
})

// 这里覆盖了$mount方法
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)

  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) { // el判断,不能是body或html
    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
  // resolve template/el and convert to render function
  if (!options.render) { 
  // 从这可以看出: 
  // 1如果配置里有render函数,template和el不会生效, 
  // 2无论是template还是el,都将会处理成render函数
    let template = options.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
            )
          }
        }
      } 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)
    }
    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

小结:entry-runtime-with-compiler.js文件中主要做的事是覆盖$mount方法

根据import Vue from ‘./runtime/index’,我们打开这个文件

/* @flow */

import Vue from 'core/index' // 第一行就是这个,看来这里不是Vue构造方法,等会去看
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
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
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
Vue.prototype.__patch__ = inBrowser ? patch : noop

// public mount method
// 实现了$mount方法
// 而$mount方法就是调用了mountComponent()
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 */
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

小结:这里实现了mount方法,但它仅仅是调用了一下mountComponent方法,我们知道,调用mount方法后,虚拟Dom将变为真实Dom,可以猜测一下mountComponent方法里会有虚拟Dom转真实Dom过程,要学习虚拟dom,这里就是入口。
这里留着以后看,先去找vue,打开core/config.js

import Vue from './instance/index' // 这里又不是构造方法,不过看到了instance,应该快了
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的构造方法,不过再向上找马上要到了,这里我们看到了initGlobalAPI,我忍不住就点开了她

/* @flow */

import config from '../config'
import { initUse } from './use'
import { initMixin } from './mixin'
import { initExtend } from './extend'
import { initAssetRegisters } from './assets'
import { set, del } from '../observer/index'
import { ASSET_TYPES } from 'shared/constants'
import builtInComponents from '../components/index'
import { observe } from 'core/observer/index'

import {
  warn,
  extend,
  nextTick,
  mergeOptions,
  defineReactive
} from '../util/index'

export function initGlobalAPI (Vue: GlobalAPI) {
  // config
  const configDef = {}
  configDef.get = () => config
  if (process.env.NODE_ENV !== 'production') {
    configDef.set = () => {
      warn(
        'Do not replace the Vue.config object, set individual fields instead.'
      )
    }
  }
  Object.defineProperty(Vue, 'config', configDef)

  // exposed util methods.
  // NOTE: these are not considered part of the public API - avoid relying on
  // them unless you are aware of the risk.
  
  
  Vue.util = { // 定义了util,里面有个extend,但并不是Vue.extend,这个util平时都没用过呀,不是看到这我都不知道有个这东西
    warn,
    extend,
    mergeOptions,
    defineReactive
  }

  Vue.set = set  // Vue.set,这个用得多
  Vue.delete = del // 这个偶尔用一下
  Vue.nextTick = nextTick // 这个面试题里碰到好多次,终于找到你在哪了

  // 2.6 explicit observable API
  Vue.observable = <T>(obj: T): T => {
    observe(obj)
    return obj
  }

  Vue.options = Object.create(null)
  ASSET_TYPES.forEach(type => {
    Vue.options[type + 's'] = Object.create(null)
  })

  // this is used to identify the "base" constructor to extend all plain-object
  // components with in Weex's multi-instance scenarios.
  Vue.options._base = Vue

  extend(Vue.options.components, builtInComponents)

  initUse(Vue) // Vue加载插件的方法
  initMixin(Vue) // Vue混入的方法
  initExtend(Vue) // 这个才是Vue.extend
  initAssetRegisters(Vue) // 这是啥,没用过
}

小结:这里发现了很多好东西呀,set、delete、nextTice、use、mixin、extend等等,想学这些东西的小伙伴们,入口已经找到啦,我们接着去找Vue的构造方法,打开 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'

// Vue的构造方法,调用_init(),_init方法在initMixin中定义
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

这里面就相当精彩了,后面这5个方法应试是Vue的核心,每一个都需要好好去看,后面我再一个个整理出来,嘻嘻!

总结一下看文件的顺序

  1. package.json:找到dev,“dev”: “rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-full-dev”,两个重要信息 1.配置文件是scripts/config.js,2.在配置文件中找web-full-dev项
  2. 打开scripts/config.js,找到web-full-dev,就知道了入口文件是web/entry-runtime-with-compiler.js
  3. 打开web/entry-runtime-with-compiler.js,在这里有引入Vue:import Vue from ‘./runtime/index’,我们就去找这个文件
  4. 打开上面的’./runtime/index’,又看到了一个Vue的引入:import Vue from ‘core/index’
  5. 打开上面的core/index,它在src文件下面,打开后又是一个引入Vue:import Vue from ‘./instance/index’
  6. 打开上面的‘./instance/index’,我们看到了Vue的构造方法

打开的这些个文件,每个里面都有一个或多个模块的入口
我也是第一次看源码,有什么写错的地方还请指出来,大家一起学习,一起进步!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值