vue 运行时 + 编译器 vs. 只包含运行时

https://cn.vuejs.org/v2/guide/installation.html#运行时-编译器-vs-只包含运行时

文档中的这个地方,说的不清楚

If you need to compile templates on the client (e.g. passing a string to the template option, or mounting to an element using its in-DOM HTML as the template), you will need the compiler and thus the full build

这部分的意思是对于以下情况会用到compiler:

  有指定template

  没指定template,也没指定render(这时候使用的就是被挂载元素的outerHtml

所以,没有使用到compiler的情况只有:没有指定template,但指定了render。 这种情况并没有画到vue的生命周期图里,真的不容易发现。

有时候我们会遇到这样的错误:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

以上提到,解决这个问题有两种方式。到谷歌必应上搜索,99%的都选择了后者,也就是使用全功能的vue(runtime+compiler),这个版本的vue文件相比仅包含runtime的版本体积要大,而且运行时的compile转换会消耗性能,compile过程其实可以放到构建过程中进行。

总结就是:如果可以的话,尽量使用runtime版的vue文件。

以下演示一个简单的runtime版vue项目 :

项目初始化,前三个依赖是vue-loader的必备依赖

npm init -y && npm install --save-dev css-loader vue-loader vue-template-compiler vue

其余文件

// app.vue
<style scoped>
    .title{
        color:red;
        text-align: center;
    }
</style>

<template>
    <div class="title">
        这是标题
    </div>
</template>

<script>
    alert("标题初始化")
</script>

// index.html
<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div >
        <app></app>
    </div>
</body>
<script src="bundle.js"></script>
</html>

// main.js
import Vue from 'vue'
import app from './app.vue'

// new Vue({
//     el:"#root",
//     render:function(c){
//         return c("app")
//     },
//     components:{
//         app
//     }
// });

// 两种初始化方式都可以
new Vue(app).$mount("#root");

// webpack.config.js
module.exports = {
    entry: {
        bundle: './main.js'
    },
    output: {
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            }
        ]
    },
    resolve: {
        extensions: [".vue",".js",".json"],
        alias: {
            'vue$': 'vue/dist/vue.runtime.js',
        }
    },
};

以上项目能正常运行。

compiler的作用在webpack引入 .vue文件的时候,就调用vue-loader来预处理过了,所以到了浏览器端运行的时候,仅仅引入vue.runtime就可以了