vite中vue-router报错requested模块does not provide an export named 'RouteRecordRaw'

6,742 阅读1分钟

完整报错信息:Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/vue-router.js? v=b7ba5df0' does not provide an export named 'RouteRecordRaw'

报错信息截图

error.png

项目技术场景

  • vue3+vite+vue-router@4.2.4
  • 创建路由时报错的
  • 因为项目比较赶、急、要快速上线(个人懒),就没有使用到TS

项目路由代码

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router' 

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: "/",
            name: "home",
            component: () => import('@/page/home/index.vue')
        },
        {
            path: "/list",
            name: "list",
            component: () => import('@/page/list/index.vue')
        },
        ......
    ]
})

报错原因和解决方案

报错原因

  • RouteRecordRawRouterOptions是搭配TS时使用的,因为项目没有用到TS类型校验
  • 所以不能出现这两个api
  • 要不然类型校验不通过,就报错啦!

解决方案

用vue3搭配vite不用TS的项目,不要出现上述两个api即可

变成这样的代码即可

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: "/",
            name: "home",
            component: () => import('@/page/home/index.vue')
        },
        {
            path: "/list",
            name: "list",
            component: () => import('@/page/list/index.vue')
        },
        ......
    ]
})

个人观点

  • 这个报错应该是vue团队没有做处理的bug
  • 可以到github上去提一个issue
  • 估计再过一段时间的某个版本就会修复了
  • 就不会出现这个bug了

项目中的小坑,分享出来,以便于大家快速解决问题(笔者被坑了20分钟才找到问题所在...)