Rails 5.2+Webpacker+Vue报错:使用仅运行时版本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.
Webpacker在安装Vue时,默认引入的是runtime-only版本的Vue——这个版本刻意去掉了模板编译器,目的是缩小打包后的文件体积。但你现在在DOM里直接写的<div id="vueapp"> {{ message }} </div>属于「inline模板」,这种模板需要Vue的编译器来实时解析,而runtime-only版本没有这个功能,所以就触发了警告。
之前用vue-rails(搭配Sprockets)没问题,是因为那个gem默认引入的是包含编译器的完整Vue版本,和Webpacker的默认配置不一样。
下面给你两个可行的解决方案:
方案1:改用Render函数(推荐)
这是Webpack生态下的最佳实践,完全不需要依赖模板编译器。修改你的hello_vue.js:
import Vue from 'vue' document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ el: '#vueapp', data: () => ({ message: "Hello Vue!" }), // 用render函数替代inline模板 render(h) { return h('div', this.message) } }) })
然后把视图里的代码改成空的容器就行:
<div id="vueapp"></div>
这样打包后的体积更小,性能也更好。
方案2:配置Webpacker使用带编译器的Vue
如果你坚持想用inline模板,可以修改Webpack配置,让它引入包含编译器的Vue版本。打开config/webpack/environment.js,添加以下配置:
const { environment } = require('@rails/webpacker') // 引入Vue loader并配置别名 const vue = require('./loaders/vue') environment.loaders.prepend('vue', vue) environment.config.set('resolve.alias', { vue$: 'vue/dist/vue.esm.js' // 指向带编译器的Vue版本 }) module.exports = environment
修改完成后重启Webpacker服务,你原来的代码就能正常运行了。不过要注意,这个方案会让打包后的文件变大一些,因为包含了模板编译器。
内容的提问来源于stack exchange,提问作者pragmatic_programmer

