vite项目中@loadable/component实现路由动态导入
- 关键知识点 import.meta.glob
Vite 支持使用特殊的 import.meta.glob 函数从文件系统导入多个模块 const modules = import.meta.glob('./dir/*.js')
- 代码配置
import React from 'react' import loadable from '@loadable/component' const modules = import.meta.glob('../containers/*/*.tsx') function LoadableCom (props: Project.General.IAnyObject): JSX.Element { const component = `/containers${props.route.component}/` const LoadableBar: any = loadable(async () => { try { // 路由动态导入 for (const path in modules) { if (path.indexOf(component) !== -1) { return modules[path]() } } } catch (error) { return import('../containers/Error/404') } }) return <LoadableBar /> } export default LoadableCom
- 上述 modules常量可以获得一个当前文件集合&#x