Vue Router4踩坑之模块不提供名为“默认”的导出

4,206 阅读1分钟

在使用 Vue3、Vite、Vue Router 开发项目时遇到的一个问题。

版本:

"vue": "^3.2.25",
"vue-router": "^4.0.12"
"vite": "^2.7.2"

在按照官方文档使用 Vue Router 时出现 bug。我想在一个模块化工程中安装使用 Vue Router,可是此时的官方文档没有此种方式的例子,我参照它在全局的 script 标签中引入的例子,自己在 router.js 写了如下代码,在 main.js 中引用,并app.use(router)

import VueRouter from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'

const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [  
        {path: '/home', component: Home},
        {path: '/about', component: About},
    ]
})
export default router

然后就出现了以下报错:

Uncaught SyntaxError: The requested module '/node_modules/.vite/vue-router.js?v=65d6b2e2' does not provide an export named 'default'

image.png

我在想既然不提供名为“默认”的导出,那我就在 main.js 直接写,不引用总该行了吧。

import { createApp } from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'

const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [  
        {path: '/home', component: Home},
        {path: '/about', component: About},
    ]
})

const app = createApp(App);
app.use(router);
app.mount('#app');

但是,还是出现报错,同样的问题只不过换了个文件。

main.js?t=1642317933837:2 Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=65d6b2e2' does not provide an export named 'default'

image.png

最后,在网上在网上找到正确的写法。

方法一:使用 createRouter 创建路由

import {createRouter, createWebHashHistory} from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {path: '/home', component: Home},
        {path: '/about', component: About},
    ]
})
export default router 

方法二:import * as VueRouter from 'vue-router'

import * as VueRouter from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'

const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [
        {path: '/home', component: Home},
        {path: '/about', component: About},
    ]
})
export default router