umi 中的路由分类两种:
配置式路由:开发者需要单独创建一个配置文件,通过各种属性或方法来实现对路由规则的配置;
约定式路由:开发者不需要手动配置,只需要按照 umi 的规则来创建路由目录和文件,umi 会自动根据文件目录将路由配置解析出来;
当项目中的路由结构比较简单,就可以使用约定式路由。如果是比较复杂的项目,都建议使用配置式路由。
一、路由模式
umi 项目中的路由模式默认是 history 模式,可以通过 history 属性来切换路由模式:
import { defineConfig } from 'umi';
export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
routes: [
{ path: '/', component: '@/pages/index' },
],
// 路由模式
history: {
type: 'hash'
},
fastRefresh: {},
});
二、配置一级路由
路由的配置,在项目根目录中的 .umirc.ts 文件中进行:
import { defineConfig } from 'umi';
export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
routes: [
{ path: '/', component: '@/pages/index' },
{ path: '/my', component: '@/pages/my' },
{ path: '/friend', component: '@/pages/friend' },
],
fastRefresh: {},
});
三、配置二级路由
import { defineConfig } from 'umi';
export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
routes: [
{
path: '/', component: '@/pages/index',
// 配置子路由
routes: [
{ path: '/discover', component: '@/pages/discover' },
{ path: '/discover/topList', component: '@/pages/topList' },
]
},
{ path: '/my', component: '@/pages/my' },
{ path: '/friend', component: '@/pages/friend' },
],
history: {
type: 'hash'
},
fastRefresh: {},
});