我在自行使用webpack搭建单页面应用框架时,引入了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.
main.js代码如下:
import Vue from 'vue';import App from './App.vue';
new Vue({
el: "#app",
template: '<App/>',
component: {App}
});
下面一起来分析下出错的原因和解决办法。
vue有两种形式的代码 compiler
(模板)模式和 runtime
模式(运行时),vue模块的package.json的main字段默认为runtime模式, 指向了"dist/vue.runtime.common.js"位置。
而在main.js文件中,初始化vue使用的是compiler模式,所以就会出现上面的错误信息。
解决办法一
将main.js初始化vue使用runtime模式,如下:
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app")
解决办法二
webpack配置文件里有个别名配置,如下:
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js' //内部为正则表达式 vue结尾的
}
}
也就是说,import Vue from ‘vue’ 这行代码被解析为 import Vue from ‘vue/dist/vue.esm.js’,直接指定了文件的位置,没有使用main字段默认的文件位置。即把配置文件别名配置修改为:
configureWebpack: {
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
}
解决办法三
那就是在引用vue时,直接写成如下即可:
import Vue from 'vue/dist/vue.esm.js'
总结,学习就是要不断采坑,同时也是在不断提升自己。
查看完整代码,详见我的仓库=>冲鸭!