vue 报错 You are using the runtime-only build of Vue where the template compiler is not available.

问题描述

学习vue-router官方教程,'起步’章节,<router-view>无效果,控制台报warn:

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

项目大体情况

  • 环境如下:

    • webpack版本:4.40.2
    • vue-cli版本:3.11.0
  • 使用vue-cli vue create xxx命令创建vue项目,采取默认配置

  • 使用npm install vue-router安装vue-router

  • 主要代码如下:

import Vue from 'vue'
import App from './App.vue'

// 0. 导入vue-router
import VueRouter from 'vue-router'
Vue.use(VueRouter)

Vue.config.productionTip = false

// 1. 定义路由组件
const Foo = {template:'<div>Foo</div>'}
const Bar = {template:'<div>Bar</div>'}
const User = {template:'<div>user {{ $route.params.id }}</div>'}

// 2. 定义路由
const routesMap = [
  { path:'/foo',component:Foo},
  { path:'/bar',component:Bar},
  { path:'/user/:id',component: User}
]

// 3. 创建router实例
const router = new VueRouter({
  mode: 'history',
  routes:routesMap
})

// 4. 创建和挂载根实例
// 通过router挂载根实例,让整个应用具有路由功能
new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

解决方案

实际上不是<router-view>的问题,而是template出了问题。

方案1

main.js中的import Vue from 'vue'更改为import Vue from 'vue/dist/vue.js'

方案2

  1. 在项目根目录创建vue.config.js文件,编写如下代码
module.exports = {
  runtimeCompiler: true
}
  1. 重新运行项目

原理

报错内容是什么意思?

你正在使用’仅有运行时环境’的Vue构建版本,该版本中template编译器不可用。要么预编译模板,使其变为render函数,或者使用’包含编译器’的Vue构建版本。

vue构建版本表

在这里插入图片描述

传送门

方案1原理

我们指定了引入vue/dist/vue.js版本,具有compiler,问题解决。

方案2原理

该解决方案来自vue-cli官方文档,传送门点我

思考:import Vue from 'Vue'到底是什么含义?

网上的很多资料说法如下:

import相当于nodejs中执行 require
执行过程如下:

  1. import Vue from ‘vue’ 解析为 const Vue = require(‘vue’)。
  2. require 判断 vue 是否为 nodejs 核心包,如我们常用的:path,fs 等,是则直接导入,否则继续往下走。
  3. vue 非 nodejs 核心包,判断 vue 是否未 ‘/’ 根目录开头,显然不是,继续往下走。
  4. vue 是否为 ‘./’、’/’ 或者 ‘…/’ 开头,显然不是,继续往下走。
  5. 以上条件都不符合,读取项目目录下 node_modules 包里的包。

按照这种说法,我查看了我的/src/node_modules/vue/package.json文件,其中部分配置如下:

"main":"/dist/vue.runtime.common.js",
"module":"dist/vue.runtime.common.js"

如果我们将vue模块的入口配置mainmodule更改为

"main":"/dist/vue.common.js"
"module":"dist/vue.common.js"

岂不是也可以加载具有编译器模块的Vue构建版本?但在实验中并没有生效…奈何小白一枚,对webpack、nodejs的机制了解不清楚,看了半天源码也没看出来个所以然…还望大神指教

新问题:官网文档提供的webpack配置方案行不通

在根目录加了webpack.config.js文件后,按照官网文档提供的配置后还是不能引入compiler。

由于针对本文的问题已经有可以用的解决方案了,对于这个新问题先占个坑,以后解决了再更~

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值