创建vue项目,将main.js中代码改成如下形式
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
components: {App},
template: `<App/>`
})
报错
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.
分析原因
vue 在初始化项目配置的时候,有两个运行环境配置的版本:Compiler 版本、Runtime 版本。 创建vue项目时没有让选择运行环境配置的版本。默认 npm 包导出的是运行时构建,即 runtime 版本,不支持编译 template 模板。
解决方案1
// import App from './App.vue'
import Vue from 'vue/dist/vue.js'
因为直接引入vue,import Vue from 'vue',引入的是node_modules中vue的package.json文件的module指定的dist/vue.runtime.esm.js版本(只包含:核心功能),这个版本是残缺的【使用残缺版是为了在打包后节省空间】,不能使用template,解决:方法1.import Vue from 'vue/dist/vue.js'引入完整版(包含:核心功能+模版解析器)
弊端:项目中一般都直接引用vue,不会指定到dist文件中的具体位置,所以这种方法一般不可取
解决方案2
new Vue({
// 将app组件放入容器中
render: h => h(App),
}).$mount('#app')
通过使用render函数接收到的createElement函数去指定具体内容
弊端:在其他文件应用vue时,还是会出现上面的问题。例如,在使用vue-router时,需要在路由组件通过
Vue.use()明确地安装路由功能,首先要引用Vue,此时,如果直接使用import Vue form 'vue',路由跳转到其他页面也会报错。所以这种方法一般不可取
解决方案3
vue.config.js配置文件中设置runtimeCompiler属性
module.exports = {
runtimeCompiler: true,
}
另一种方法是使用包含编译器的构建版本,可以通过在 webpack.config.js 中配置 resolve.alias 来实现。例如:
module.exports = {
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
}