Vue3中vite动态import引入打包报错解决
import {RouteRecordRaw,createRouter,createWebHistory,useRoute,} from "vue-router"// @ts-ignoreimport util from "/@libs/util"// import Layout from '/@views/layout/Layout.vue'// @ts-ignoreimport store f
·
Vite 支持使用特殊的 import.meta.glob 函数从文件系统导入多个模块,需要使用这个方式
import {
RouteRecordRaw,
createRouter,
createWebHistory,
useRoute,
} from "vue-router"
// @ts-ignore
import util from "/@libs/util"
// import Layout from '/@views/layout/Layout.vue'
// @ts-ignore
import store from "/@store/index"
import Layout from "../layout/index.vue"
// 进度条
// @ts-ignore
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { useStore } from "vuex"
//Vite 支持使用特殊的 import.meta.glob 函数从文件系统导入多个模块
const modules = import.meta.glob("../views/**/**.vue")
const routes: RouteRecordRaw[] = [
//路由一定要与modules导入的一致(const modules =import.meta.glob("../views/**/**.vue"))
{
path: "/login",
name: "login",
component: modules["../views/system/login/index.vue"],//使用../views/
},
// 后台首页
{
path: "/",
name: "home",
component: Layout,
redirect: { path: "/index" },
meta: {
title: "首页",
},
children: []
]
const router = createRouter({
history: createWebHistory(),
routes,
})
//处理动态路由 因为vue3没有addRoutes 只能遍历一个一个加
export const routerPackag = function (routers: any) {
if (routers) {
routers.filter((itemRouter: any) => {
if (itemRouter.component != "Layout") {
router.addRoute("home", {
path: `${itemRouter.path}`,
name: itemRouter.name,
meta: {
title: itemRouter.name,
},
component:
//需要用vite规定的导入方式导入,否则打包后部署到服务器报错找不到动态导入的文件,
//对应上方的const modules = import.meta.glob("../views/**/**.vue")
//使用/* @vite-ignore */则不会在开发是报错
modules[/* @vite-ignore */`../views/${itemRouter.component}`],
})
}
if (itemRouter.children && itemRouter.children.length) {
routerPackag(itemRouter.children)
}
return true
})
}
}
//动态加路由
let allRouter: any = localStorage.getItem("info")
if (JSON.parse(allRouter)) {
routerPackag(JSON.parse(allRouter).routerList)
}
//路由守卫
router.beforeEach(async (to, from, next) => {
const info = await store.dispatch("sys/user/load")
const token: any = info.token ? info.token : ""
NProgress.start()
// 关闭搜索面板
if (to.path == "/login") {
next()
} else {
if (token && token !== "undefined") {
console.log(token, "token")
next()
} else {
// 没有登录的时候跳转到登录界面
// 携带上登陆成功之后需要跳转的页面完整路径
next("/login")
// 关闭搜索面板
NProgress.done()
}
}
})
router.afterEach((to) => {
// 进度条
NProgress.done()
// 更改标题
util.title(to.meta.title)
})
export default router
核心:
//vite的引入方式
const modules = import.meta.glob("../views/**/**.vue")
//"home"加到home的children中
router.addRoute("home", {
path: `${itemRouter.path}`,
name: itemRouter.name,
meta: {
title: itemRouter.name,
},
component:
modules[/* @vite-ignore */`../views/${itemRouter.component}`],
})
更多推荐
已为社区贡献2条内容
所有评论(0)