Runtime-Compiler和Runtime-Only的区别

我们使用 vue init 命令创建脚手架的时候,会有如下选择

  • Runtime + Compiler
  • Runtime-Only

那么它们究竟有什么区别呢,今天我们就来探讨一下

在这里插入图片描述
首先,我们分别通过这两种方式,创建Vue脚手架。我们来看一下两者的 main.js 有什么不一样
在这里插入图片描述
区别很明显,在 Vue 实例中,runtime-compiler 创建的项目中的参数是 compoennts 和 template,而在 runtime-only创建的项目中,参数是 render函数,这是他们最大的区别

组件渲染过程

其次,我们再来了解一下,组件是怎么被渲染到页面当中去的,这对我们理解上述问题起到关键性的作用
template --> ast --> render --> vDom --> 真实的Dom --> 页面

ast:抽象语法树
vDom:虚拟Dom(virdual-dom )

可以发现,template最终还是会被渲染为 render函数

即无论通过何种方式创建,最终都是渲染为render函数来渲染页面的。这点我们从vue源码的入口文件(src\platforms\web\entry-runtime-with-compiler.js)中也能得出此结论,源码如下

 // 当render不存在,则判断template,不存在再判断el
  if (!options.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)
    }

runtime-only

  • 我们在使用 runtime-only 的时候,需要借助 webpack的loader工具,将 .vue文件编译为JavaScript,因为是在编译阶段做的,所以它只包含运行时的 Vue.js 代码,所以代码体积会更轻量

  • 在将 .vue 文件编译为 JavaScript文件的过程中会将组件中的 template 模版编译为 render 函数,所以我们得到的是 render 函数的版本。所以运行的时候是不带编译的,编译是在离线的时候做的

  • template 会通过 vue-template-compiler 转换为 render 函数

runtime-compiler

  • 因为在Vue中,最终渲染都是通过 render函数,如果写 template 属性,则会编译为 render 函数,那么这个编译过程会发生在运行时,所以需要带有编译器的版本
  • 编译过程会对性能有一定的损耗

结论

runtime-only: 将template在打包的时候,就已经编译为 render函数
runtime-compiler: 在运行的时候,才去编译 template

结果: 发布生产的时候,runtime-only 构建的项目代码体积更小,运行速度更快

线上推荐使用runtime-only构建项目

开发阶段推荐使用runtime-compiler构建项目

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值