配置修改
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
open: true,
proxy: {
'/api': {
target: 'http://',
changeOrigin: true,
}
}
},
resolve: {
alias: { // 打包相关能尽量给绝对路径,就给绝对
// 程序运行的目录 相对下面的src => 的绝对路径
'@': path.resolve(__dirname, './src'),
'~': path.resolve(__dirname, './'), // 项目根目录
}
}
})
vite-env.d.ts
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
tsconfig.json
{
"compilerOptions": {
"baseUrl": "./" // 解析非相对模块的基础地址,默认是当前目录
"paths": { // 路径映射,相对于baseUrl
"@/*": ["src/*"]
}
}
}
动态路由设置
// 加载views下的所有组件到模块
const modules = (import.meta as any).glob('../views/**/*.vue');
function asyncRoutersHandler(routers: any[]) {
return routers.map((route: any) => {
// 判断"component": "Layout"
if (route.component === 'Layout') {
route.component = Layout
} else {
const comPath = route.component
// 没有变量, 作为${route.component}直接使用
// route.component = () => import(`../views/${comPath}.vue`)
// Vite动态加载
route.component = modules[`../views/${comPath}.vue`];
}
// 如果有child则递归处理
if (route.children) {
route.children = asyncRoutersHandler(route.children)
}
return route
})
}