一、两个版本对应的文件名
- vue.js 完整版 runtime-comiler
vue.min.js 完整版 (生产环境)--无注释- vue.runtime.js 只包含运行时版 runtime-only
vue.runtime.min.js 只包含运行时版 (生产环境)--无注释
二、两个的版本区别:
- vue.js 完整版
1)完整版同时包含编译器(compiler)和运行时(runtime),编译器(compiler)占总体积的40%
2)视图写在HTML或者 template 选项中
3)使用时,需要引入 vue.min.js
4)webpack 引入时,需要配置alias,同时在 @vue/cli 引入时,需要额外配置- vue.runtime.js 只包含运行时版
1)运行时版本中没有编译器(compiler) 2)只支持render函数,不能识别template;视图写在 render 函数里,用 h 来创建标签,h 可以替换成任意字母,但一般默认使用h。.vue文件中的template也是被vue-template-compiler翻译成了render函数,所以只能在.vue里写 template
**
1.template 和 render使用方法
- template:完整版 Vue 可直接写 template,然后通过编译器解析成ast,然后生成render方法
// 需要编译器Compiler
new Vue({
template: '<div>{{ hi }}</div>'
})
2.render:运行时版Vue直接使用render,用h函数生成虚拟dom
// 不需要编译器Compiler
new Vue({
render (h) {
return h('div', this.hi)
}
})
2.两种模式生成的 脚手架 即(代码模板)主要区别在 main.js 中,其它基本上是一样的:
3.运行过程区别对比:
1.runtime + compiler 中 Vue 的运行过程
对于 runtime-compiler 来说,它的代码运行过程是:template -> ast -> render -> virtual dom -> UI
- 首先将vue中的template模板进行解析解析成abstract syntax tree (ast)抽象语法树
- 将抽象语法树在编译成render函数
- 将render函数再翻译成virtual dom(虚拟dom)
- 将虚拟dom显示在浏览器上
2.runtime-only 中 Vue 的运行过程
对于 runtime-only来说,它是从 render -> virtual dom -> UI
- 可以看出它省略了从template -> ast -> render的过程
- 所以runtime-only比runtime-compiler更快,代码量更少
- runtime-only 模式中不是没有写 template ,只是把 template 放在了
.vue的文件中了,并有一个叫vue-template-compiler的开发依赖时将.vue文件中的 template 解析成 render 函数。 因为是开发依赖,不在最后生产中,所以最后生产出来的运行的代码没有template
三、实际应用
在实践过程中,我们往往使用的是运行时版本,并且往往和vue-loader和vue文件搭配使用。因为为了保证用户体验,使用户下载的JS文件的体积更小,所以Vue必须放弃某些功能,所以运行时版只支持h函数。但为了方便用户可以直接在vue文件里写HTML标签,而不写h函数,Vue的作者就写了vue-loader来把vue文件里的HTML模板转换为h函数。
四、runtime-only 更快的原因:
runtime-only比runtime-compiler更快,是因为它省略了运行过程中的第一点,如果是runtime-compiler,那么main.js中就会出现template从而在运行时直接在客户端编译解析,同时增加了项目大小。
而 runtime-only 模式中不是没有写 template ,只是把 template 放在了.vue 的文件中了,会使用vue-loader、vue-template-compiler的插件,因为是开发时依赖,打包的时候就将.vue文件中的 template 解析成 render 函数了,不需要在客户端编译,所以最后打包出来的运行的代码没有template
五、总结
如果在之后的开发中,你依然使用template,就需要选择 Runtime + Compiler
如果你之后的开发中,使用的是.vue文件夹开发,那么可以选择 Runtime-only
六、扩展
在使用 vue-cli 脚手架构建项目时,会遇到一个构建选项 Vue build,有两个选项,Runtime + Compiler和Runtime-only:
· Runtime + Compiler: recommended for most users
(运行程序+编译器:推荐给大多数用户)
· Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specificHTML) are ONLY allowed in .vue files - render functions are required elsewhere
(仅运行程序: 比上面那种模式轻大约 6KB min+gzip,但是 template (或任何特定于vue的html)只允许在.vue文件中使用——其他地方用需要 render 函数)