icejs 推荐使用 配置式路由 进行路由管理。但同时也支持 文件约定式路由 方案,当项目中不存在 src/routes.[ts|js] 文件时,则会自动开启文件约定式路由模式。

文件约定式路由

顾名思义,文件约定式路由会根据项目的目录结构自动生成路由配置,无需开发者手动配置。文件约定式路由虽然不需要用户手动配置,但因为路由配置本身存在很多规则,因此约定式路由也需要约定一系列的目录结构设计,这本身也有一定的学习成本。

基础路由

假设 pages 的目录结构如下:

  1. src/pages
  2. └── About
  3. └── index.tsx
  4. └── Dashboard
  5. ├── a.tsx
  6. └── b.tsx

那么,框架自动生成的路由配置如下:

  1. export default [
  2. {
  3. path: '/about',
  4. exact: true,
  5. component: PageAbout,
  6. },
  7. {
  8. path: '/dashboard/a',
  9. exact: true,
  10. component: PageDashboardA,
  11. },
  12. {
  13. path: '/dashboard/b',
  14. exact: true,
  15. component: PageDashboardB,
  16. },
  17. ];

404 路由

如果 src/pages/404.[jsx|tsx] 或者 src/pages/404/index.[jsx|tsx] 文件存在,则将它作为 404 页面

index 路由

如果 src/pages/index.[jsx|tsx] 文件存在,则会自动映射到 / 的路由。

嵌套路由

框架约定页面目录下存在名为 _layout.[jsx|tsx] 时,会产生一个嵌套路由,当前目录和子目录均为子路由。

假设 pages 的目录结构如下:

  1. src/pages
  2. └── About
  3. ├── _layout.tsx
  4. ├── a.tsx
  5. └── b.tsx
  6. └── Dashboard
  7. └── index.tsx

那么,框架自动生成的路由配置如下:

  1. [
  2. {
  3. path: '/about',
  4. exact: false,
  5. component: LayoutAbout,
  6. children: [
  7. {
  8. path: '/a',
  9. exact: true,
  10. component: PageAboutA,
  11. },
  12. {
  13. path: '/b',
  14. exact: true,
  15. component: PageAboutB,
  16. },
  17. ],
  18. },
  19. {
  20. path: '/dashboard',
  21. exact: true,
  22. component: PageDashboard,
  23. },
  24. ];

动态路由

框架约定定义带参数的动态路由,需要创建对应的以下划线作为前缀的文件或目录。

  • 路径中 $ 作为文件夹或文件名的首个字符,标识一个动态路由,如 src/pages/app/$uid.tsx 会生成路由 /app/:uid
  • 路径中文件夹或文件名的首个和最后一个字符同时为 $,标识一个可选的动态路由,如 src/pages/app/$uid$.tsx 会生成路由 /app/:uid?

假设 pages 的目录结构如下:

  1. src/pages
  2. └── repo
  3. ├── $pid.tsx
  4. └── index.tsx
  5. └── $uid$.tsx

那么,框架自动生成的路由配置如下:

  1. export default [
  2. {
  3. path: '/repo/:pid',
  4. exact: true,
  5. component: PageRepo$pid,
  6. },
  7. {
  8. path: '/repo',
  9. exact: true,
  10. component: PageRepo,
  11. },
  12. {
  13. path: '/:uid?',
  14. exact: true,
  15. component: Page$uid$,
  16. },
  17. ];

全局 Layout

如果 src/layouts/index.[jsx|tsx] 文件存在,则将它默认作为全局 layout

路由配置

运行时配置

详见

构建配置

build.json 中,我们也可以自定义一些构建配置:

  1. {
  2. "router": {
  3. // ...options
  4. }
  5. }

options:

  • configPath: 仅配置式路由,类型 string,默认值 'src/routes.[t|j]s',自定义配置式路由文件的地址
  • caseSensitive: 仅约定式路由,类型 boolean,默认值 false, 根据文件名转换为路由时是否大小写敏感
  • ignoreRoutes: 仅约定式路由,类型 string[],默认值 [],忽略指定路由的生成
  • ignorePaths: 仅约定式路由,类型 string[],默认值 ['components'],生成路由时忽略指定目录