Vue-cli 4.x / Vue-cli 3.x 中报 You are using the runtime-only build of Vue where the template compiler is not available

在 Vue-cli 4.x / Vue-cli 3.x 项目中报:[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. 警告,导致这问题的常见原因是用户习惯地把 Vue 2.x 项目中的 main.js 里面的下面代码段拷过来直接覆盖 Vue-cli 4.x / Vue-cli 3.x 初始生成中的 main.js 的下面代码段,忽略了其中之间的差异。

Vue 2.x 初始项目 main.js 默认代码段:

new Vue({
  el: '#app',
  router: router,
  store: store,
  template: '<App/>', // 不同之处是这里使用了 template + components 启动项目
  components: { App }
})

Vue-cli 4.x / Vue-cli 3.x 初始项目 main.js 默认代码段:

new Vue({
  router,
  store,
  render: h => h(App) // 不同之处是这里使用了 render + $mount 直接启动项目
}).$mount('#app') 

解决方案(两种都可以【建议使用第一种】)

解决方案 一、最简单的解决方式就是直接把 Vue-cli 4.x / Vue-cli 3.x 项目中 main.js 的代码改回来使用 render + $mount 的方式就行了。

解决方案 二、修改项目根目录下 vue.config.js 文件(如果没有就创建一个)

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm.js' // 预编译 + 运行时,适用于 dev 环境
      }
    }
  }
  // 其他配置代码 ...
}

总结

完整版 vue.esm.js,是预编译 + 运行时,也就是模板字符串和现在最常用的单文件组件 .vue 文件,需要经过它预编译转化成纯 javascrit,然后再运行,适用于开发环境,Vue-cli 2.x 用此方式来运行。但 Vue-cli 4.x / Vue-cli 3.x,则不一样,默认是使用 render + $mount 直接启动项目,不走预编译,使用的是非完整版的 vue.runtime.esm.js 。生产环境用的也是 vue.runtime.esm.js,比完整版小 30% 左右,前端性能更优。