美文网首页
vue 源码 - 02 打包入口

vue 源码 - 02 打包入口

作者: Lisa_Guo | 来源:发表于2019-12-27 11:39 被阅读0次

    src/platforms/web目录下包含了用于web的打包入口文件。目录结构如下

    |-- compiler                // 编译器相关文件    
        |-- directives          // vue自带指令:v-html、v-model,v-text
        |-- modules
        |-- index.js             
    |-- runtime                 // 运行时相关文件
        |-- components          // vue自带组件:transition,transitionGroup
        |-- directives          // vue自带指令:v-modle、v-show
        |-- modules
        |-- index.js
    |-- server                   // 服务器渲染相关文件
    |-- utils                      // 通用工具类
    
    |-- entry-compiler.js      // 编译器入口文件
    |-- entry-runtime-with-compiler.js   // 完整版入口文件
    |-- entry-runtime.js                         // 运行时版入口文件
    |-- entry-server-basic-renderer.js   // 基础版服务器渲染入口文件
    |-- entry-server-renderer.js             // 服务器渲染入口文件
    

    运行时版本的入口文件为src/platforms/web/entry-runtime.js,该文件仅输出./runtime/index.js的内容。
    代码基本流程为:

    1. 导入vue的核心定义
    2. 定义平台相关的配置信息、指令、组件
    3. 定义vue.prototype.$mount
    4. 输出定制后的vue定义
    /* runtime/index.js */
    import Vue from 'core/index'
    import platformDirectives from './directives/index'
    import platformComponents from './components.index'
    import {query,  mustUseProp,  isReservedTag,  isReservedAttr,  getTagNamespace,  isUnknownElement } from 'web/util/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
    Vue.prototype.$mount = function (
      el?: string | Element,
      hydrating?: boolean
    ): Component {
      el = el && inBrowser ? query(el) : undefined
      return mountComponent(this, el, hydrating)
    }
    
    ...
    
    export default Vue
    

    完成版在runtime运行版的定制基础上,重新定义了$mount函数: 将template模板编译为render函数,然后再正常mount

    import Vue from './runtime/index'
    ...
    const mount = Vue.prototype.$mount
    Vue.prototype.$mount = function(el, hydrating) {
        ...
        const options = this.$options
        // resolve template/el and convert to render function
        if(!options.render) {
           let template = options.tempate
           ...
           const { render , staticRenderFns } = conpileToFunctions(tempalte, {}, this)
           options.render = render
           options.staticRenderFns = staticRenderFns
        }
    
        return mount.call(this, el, hydrating)
    }
    

    相关文章

      网友评论

          本文标题:vue 源码 - 02 打包入口

          本文链接:https://www.haomeiwen.com/subject/erakoctx.html