vue源碼分析(一)-源碼入口

源碼入口分析

備註:僅用於本身學習源碼過程當中的總結,不少不詳細和錯誤的部分後面優化
vue提供不一樣的平臺和版本,瀏覽器環境版本包括:Runtime only版本和Runtime + compiler版本。 Runtime + compiler版本:new Vue({template: '<div>{{ hi }}</div>'}),須要將template中的字符串編譯成render函數,須要用到compiler,具體在scripts\config.jshtml

const builds = {
  'web-runtime-cjs-dev': {
    entry: resolve('web/entry-runtime.js'),
    dest: resolve('dist/vue.runtime.common.dev.js'),
    format: 'cjs',
    env: 'development',
    banner
  },
  ...
  'web-full-cjs-dev': {
    entry: resolve('web/entry-runtime-with-compiler.js'),
    dest: resolve('dist/vue.common.dev.js'),
    format: 'cjs',
    env: 'development',
    alias: { he: './entity-decoder' },
    banner
  },
  ...
 }

本文分析runtime + complier版本,entry屬性值就是Vue源碼入口,接下來查看web/entry-runtime-with-compiler.jsvue

import Vue from './runtime/index'
...
// 將runtime/index.js中定義的mount方法緩存
const mount = Vue.prototype.$mount
// 重寫$mount
// runtime + compiler版本的mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean // 和服務器渲染有關
): Component {
  el = el && query(el)

  /* istanbul ignore if */
  // el不能時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
  // resolve template/el and convert to render function
  // 若是沒有定義 render 方法,則會把 el 或者 template 字符串轉換成 render 方法
  if (!options.render) {
    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
            )
          }
        }
      } 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')
      }
      // 將template轉換成render函數compileToFunctions
      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')
      }
    }
  }
  // 這裏調用的mount是上面被緩存的mount
  return mount.call(this, el, hydrating)
}

這裏的Vue仍是經過import引入,一路向上找,最終找到src\core\instance\index.jsnode

// 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是什麼
  // initMixin給Vue添加此方法
  this._init(options)
}
// 初始化
// if (vm.$option.el) {
//   $mount負責掛載
//   vm.$mount(vm.$option.el)
// }
initMixin(Vue)
// 初始化state
// Vue.prototype.$set = set
// Vue.prototype.$delete = del
// Vue.prototype.$watch = function
stateMixin(Vue)
// 事件
// $on,$emit,$once,$off和本身寫的class bus沒有太大區別
// $emit觸發當前組件的事件
eventsMixin(Vue)
// _update !!!!!!!!!!!!!!!!
// forceUpdate,destroy
lifecycleMixin(Vue)
// 渲染
// nextTick
// _render !!!!!!!!!!!!
renderMixin(Vue)

export default Vue

能夠看到Vue的本質是一個function,之因此用function而沒有用es6的class,是由於在後續會在Vue函數原型上掛載了不少api相對於class更方便,Vue是經過xxxMixin調用不一樣目錄下的方法組裝成完整Vuees6

總結

  1. package.json中的script標籤中的build命令查找項目源碼入口,適用於其餘源碼閱讀入口
  2. vue的底層是一個構造函數,沒有使用es的class方便原型掛載api擴展各個模塊內容
相關文章
相關標籤/搜索