最近在改老项目,将webpack迁移到vite提高下速度 首先来看下默认静态加载路由,我们只需要在router/index.js直接配置好就可以了
当然默认的情况 component: () => import('../views/HomeView.vue') 是这样的如果需要用@替代..需要在在vite.config.js中增加下配置
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
在webpack中动态加载使用如下,就可以了
export const loadView = (view) => {
if (process.env.NODE_ENV === 'development') {
return (resolve) => require([`@/views/${view}`], resolve)
} else {
// 使用 import 实现生产环境的路由懒加载
return () => import(`@/views/${view}`)
}
}
但是在vite中语法就变了,require() 是 CommonJS 语法,Vite 不支持,需要用import.meta.glob来实现,下面是相对路径使用,相对路径使用要注意当前方法引入对应根目录的层级
//代码文件顶部增加
const modules = import.meta.glob('../views/**/*')
//然后定义loadView 方法
export const loadView = (view) => {
return modules[`../views/${viewPath}.vue`] // 使用相对路径
}
在这里比较推荐使用相对路径来实现
//代码文件顶部增加
const modules = import.meta.glob('/src/views/**/*')
export const loadView = (view) => {
return modules[`/src/views/${viewPath}.vue`] // 使用绝对路径
}
说明一下如果从后端获取的动态组件路径是带.vue文件名字的可以忽略
最后又完善了一下增加了一些模糊匹配规则
/src/views/${viewName}.vue
/src/views/${viewName}/index.vue
/src/views/${viewName}/${viewName}.vue
完整的loadView 方法
export const loadView = (view) => {
// 统一处理:无论后端是否带 .vue,都确保有后缀
const viewName = view.replace(/\.vue$/, '')
const possiblePaths = [
`/src/views/${viewName}.vue`,
`/src/views/${viewName}/index.vue`,
`/src/views/${viewName}/${viewName}.vue`,
]
for (const path of possiblePaths) {
// const loader = modules[path]
if (modules[path]) {
console.log('✅ 匹配组件:', path)
return modules[path]
}
}
console.error(`未找到页面组件: ${viewName}`)
console.log('可用页面组件:', Object.keys(modules))
return null
}
演示demo