ant-design-pro Documentation

‍💻👩🏻‍💻 Use Ant Design like a Pro!

38,851 stars TypeScript TypeScript 1 file · ~12,097 tokens #admin#ant-design#antd#antv#boilerplate#dashboard#enterprise#react
RAW Doc

Technical Documentation: ant-design/ant-design-pro

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)

Ant Design Pro

Features

  • :bulb: TypeScript: A language for application-scale JavaScript
  • :scroll: Blocks: Build page with block template
  • :gem: Neat Design: Built on Ant Design 6 specification
  • :triangular_ruler: Common Templates: Typical templates for enterprise applications
  • :rocket: State of The Art Development: Newest development stack of React 19/Umi Max 4/antd 6/utoopack
  • :iphone: Responsive: Designed for variable screen sizes
  • :art: Theming: Customizable theme with Tailwind CSS v4 + antd-style
  • :globe_with_meridians: International: Built-in i18n solution
  • :gear: Best Practices: Solid workflow to make your code healthy
  • :1234: Mock development: Easy to use mock development solution
  • :robot: AI Assistant: Built-in AI chatbot page powered by Ant Design X
  • :white_check_mark: UI Test: Fly safely with unit and e2e tests

Templates

text
- Welcome
- Dashboard
  - Analysis
  - Monitor
  - Workplace
- Form
  - Basic Form
  - Step Form
  - Advanced Form
- List
  - Search List (Articles/Projects/Applications)
  - Table List
  - Basic List
  - Card List
- Profile
  - Basic Profile
  - Advanced Profile
- Result
  - Success
  - Fail
- Exception
  - 403
  - 404
  - 500
- Account
  - Account Center
  - Account Settings
- AI Assistant
- User
  - Login
  - Register
  - Register Result

Usage

Get Started

Clone or download this repository to your local machine:

bash
git clone --depth=1 https://github.com/ant-design/ant-design-pro.git myapp
cd myapp

Installation

bash
npm install

Development

bash
# Start development server (full version by default)
npm start

Simplify to Simple Version

This project includes all blocks by default. If you need a minimal version, run:

bash
npm run simple

This will:

  • Remove extra page directories (dashboard, form, list/*, profile, result, exception, account, etc.)
  • Remove extra mock files
  • Replace routes with simple version
  • Remove extra dependencies from package.json

Note: This operation is irreversible and will permanently delete files.

Build

bash
npm run build

AI Skills (Claude Code)

This project ships with two built-in Claude Code Skills in .claude/skills/:

Skill Trigger Description
/pro-upgrade "upgrade pro", "update to latest" Auto-upgrade to the latest Ant Design Pro version. Diffs the latest template, merges framework changes while preserving your business code.
/antd antd-related code or questions Query antd component APIs, props, tokens, demos; lint for deprecated usage; migrate between versions — all via @ant-design/cli.

Usage in Claude Code:

bash
# Upgrade the project to latest Pro version
/pro-upgrade

# Query antd component info, debug issues, run lint, etc.
/antd

💡 If your project was cloned from this repo, these skills are already included — no installation needed. To get the latest skill definitions, pull the updates from the template or run npx skills add ant-design/ant-design-pro to refresh them.

Browsers support

Modern browsers.

Edge Firefox Chrome Safari
Edge last 2 versions last 2 versions last 2 versions

Contributing

Any type of contribution is welcome, here are some examples of how you may contribute to this project:

  • Use Ant Design Pro in your daily work.
  • Submit issues to report bugs or ask questions.
  • Propose pull requests to improve our code.

Cheatsheet.En US (`docs/cheatsheet.en-US.md`)

Ant Design Pro Cheatsheet

🎉 What's New in v6

  • React 19 + antd 6 + Umi Max 4: Full upgrade to the latest stack, powered by utoopack (Turbopack)
  • Style Overhaul: Less → Tailwind CSS v4 + antd-style + CSS Modules, CSS variable theming enabled
  • AI Assistant Page: Chat interface example built with Ant Design X
  • React Query: Migrated from useRequest to @tanstack/react-query
  • Biome: Replaces ESLint + Prettier for unified linting and formatting
  • Cloudflare Worker Backend: Standalone demo API deployment using Hono
  • And more: Route prefetch, skeleton Loading, D3 map, Cheatsheet docs, moment → dayjs, class → functional components

→ View full changelog

Getting Started

Create a project:

bash
git clone --depth 1 https://github.com/ant-design/ant-design-pro.git my-project
cd my-project
npm install

The project offers two modes:

  • Full mode: Includes all demo pages (Dashboard, Forms, Lists, Access, etc.), great for reference and learning
  • Simple mode: Only keeps login page and basic layout, ideal for starting from scratch

Switch to simple mode:

bash
git add -A && git commit -m "chore: save before simple"  # Commit first to allow revert
npm run simple                                             # Remove demo pages and unused deps
npm install                                                # Update dependencies

💡 Start with full mode to learn the project structure, then switch to simple mode for development.

Directory structure:

text
├── config/           # Configuration (routes, proxy, theme)
│   ├── config.ts     # Main config
│   ├── routes.ts     # Route definitions
│   ├── defaultSettings.ts  # Layout & theme settings
│   └── proxy.ts      # Dev proxy config
├── mock/             # Mock data
├── src/
│   ├── components/   # Shared components
│   ├── locales/      # i18n resources
│   ├── models/       # Global data models
│   ├── services/     # API service layer
│   ├── utils/        # Utility functions
│   ├── access.ts     # Permission definitions
│   └── app.tsx       # Runtime configuration
├── docs/             # Project documentation
└── types/            # Type declarations

Common commands:

Command Description
npm start Start dev server (UMI_ENV=dev, with Mock)
npm run dev Start dev server (UMI_ENV=dev, no Mock)
npm run start:no-mock Start without Mock
npm run start:pre Pre-production environment
npm run start:test Test environment
npm run build Build for production
npm run preview Preview built output (run npm run build first, port 8000)
npm run preview:build Build and preview (port 8000)
npm run deploy Build and deploy to GitHub Pages
npm run analyze Analyze bundle size
npm run lint Lint (Biome + TypeScript)
npm run biome Auto-fix with Biome
npm test Run tests
npm run test:coverage Test with coverage
npm run test:update Update test snapshots
npm run tsc Type check without emitting
npm run i18n-remove Remove i18n wrappers (locale=zh-CN)
npm run record Record request data for login scene
npm run openapi Generate API code from OpenAPI schema
npm run simple Strip demo pages and unused deps

💡 UMI_ENV switches environment configs, mapping to different proxy rules in config/proxy.ts.

💡 npm run simple removes demo pages (dashboard, form, list etc.) and unused dependencies (plots, etc.), replacing with minimal routes. Ideal for starting from scratch. Commit your code first so you can revert if needed.

Build tool: This project uses utoopack (a next-gen bundler powered by Turbopack) as the default build tool, configured via the utoopack field in config/config.ts. utoopack is Webpack-compatible and supports module.rules for custom loaders.

→ See umi Getting Started, utoo Docs

Routes & Menu

Route config is in config/routes.ts:

ts
// File: config/routes.ts
export default [
  {
    path: '/welcome',
    name: 'welcome',     // maps to menu.welcome i18n key
    icon: 'home',
    component: './Welcome',
  },
  {
    path: '/admin',
    name: 'admin',
    icon: 'crown',
    access: 'canAdmin',  // route-level access control
    routes: [...],
  },
  { path: '/', redirect: '/dashboard/analysis' },
  { component: '404', path: './*' },
];

Route navigation:

tsx
import { useNavigate, useParams, useLocation } from '@umijs/max';

const navigate = useNavigate();
navigate('/dashboard');        // navigate
navigate(-1);                  // go back

const { id } = useParams();   // dynamic param /user/:id
const location = useLocation(); // current route info

Menu & access: The access field in route config controls menu visibility — unauthorized routes won't appear in the menu.

💡 The name field is automatically mapped to menu.xxx i18n keys. Configure translations in src/locales/.

→ See umi Routes, Umi Max Layout & Menu

Layout

ProLayout config is in config/defaultSettings.ts:

ts
// File: config/defaultSettings.ts
export default {
  navTheme: 'light',               // nav theme: light / dark
  colorPrimary: '#1890ff',         // primary color
  layout: 'mix',                   // layout mode: side / top / mix
  contentWidth: 'Fluid',           // content width: Fluid / Fixed
  fixedHeader: false,              // fixed header
  fixSiderbar: true,               // fixed sidebar
  colorWeak: false,                // color weak mode
  title: 'Ant Design Pro',         // site title
  logo: 'https://...',             // logo URL
  iconfontUrl: '',                 // iconfont URL
  token: {},                       // ProLayout token for fine-grained style customization
};

Layout modes:

  • side — Side navigation
  • top — Top navigation
  • mix — Top + side mixed navigation

Page container:

tsx
import { PageContainer } from '@ant-design/pro-components';

const Page = () => (
  <PageContainer
    header={{ title: 'Page Title' }}
    content="Page description"
  >
    {/* Page content */}
  </PageContainer>
);

Custom areas: Top-right src/components/RightContent, footer src/components/Footer.

→ See Umi Max Layout & Menu

Data Flow

useModel — lightweight global state: Create a file in src/models/ to auto-register:

ts
// File: src/models/counter.ts
import { useState } from 'react';

export default function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(c => c + 1);
  return { count, increment };
}
tsx
// Use in any component
import { useModel } from '@umijs/max';

const { count, increment } = useModel('counter');

useRequest — data fetching:

tsx
import { useRequest } from '@umijs/max';

const { data, loading, error } = useRequest(getUserInfo);

React Query — server state management:

tsx
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

// Query
const { data, isLoading } = useQuery({
  queryKey: ['user', id],
  queryFn: () => getUser(id),
});

// Mutation
const mutation = useMutation({
  mutationFn: updateUser,
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['user'] });
  },
});

Initial state — getInitialState: Define in src/app.tsx, accessible globally:

tsx
// File: src/app.tsx
export async function getInitialState() {
  const currentUser = await fetchUserInfo();
  return { currentUser };
}

// Use in components
import { useModel } from '@umijs/max';
const { initialState } = useModel('@@initialState');

💡 getInitialState runs once on app startup, ideal for fetching global info (user identity, permissions).

→ See Umi Max Data Flow

Request

Request config is in src/app.tsx:

ts
// File: src/app.tsx
export const request: RequestConfig = {
  baseURL: 'https://api.example.com',
  timeout: 10000,
  requestInterceptors: [],   // request interceptors
  responseInterceptors: [],  // response interceptors
};

Error handling is in src/requestErrorConfig.ts, customize error code mapping and notification logic.

Using request:

tsx
import { request } from '@umijs/max';

// GET
const data = await request('/api/users', { params: { page: 1 } });

// POST
await request('/api/users', { method: 'POST', data: { name: 'test' } });

OpenAPI code generation:

bash
npm run openapi

Auto-generates API calling code under src/services/ based on config/oneapi.json.

💡 Generated code uses import { request } from '@umijs/max' directly — no manual wrapping needed.

→ See Umi Max Request

Permissions

Define permissions in src/access.ts:

ts
// File: src/access.ts
export default function access(initialState: { currentUser?: API.CurrentUser }) {
  const { currentUser } = initialState;
  return {
    canAdmin: currentUser?.access === 'admin',
    canUser: !!currentUser,
  };
}

Route-level access: Add access field in route config:

ts
{ path: '/admin', access: 'canAdmin' }

Component-level access:

tsx
import { Access, useAccess } from '@umijs/max';

// Declarative
<Access accessible={access.canAdmin}>
  <AdminPanel />
</Access>

// Imperative
const access = useAccess();
if (access.canAdmin) { /* ... */ }

→ See Umi Max Permissions

Internationalization

Config in config/config.ts:

ts
locale: {
  default: 'zh-CN',
  antd: true,         // sync antd component locale
  baseNavigator: true, // follow browser language
},

File structure:

text
src/locales/
├── zh-CN.ts        # Chinese entry
├── zh-CN/
│   ├── menu.ts     # Menu translations
│   ├── pages.ts    # Page translations
│   └── ...
├── en-US.ts        # English entry
└── en-US/
    └── ...

Usage:

tsx
import { useIntl, FormattedMessage } from '@umijs/max';

// Hook
const intl = useIntl();
intl.formatMessage({ id: 'menu.welcome' });

// Component
<FormattedMessage id="menu.welcome" />

Switch locale:

tsx
import { setLocale } from '@umijs/max';
setLocale('en-US', false);  // false = no page reload

→ See Umi Max i18n

Styling

CSS Modules: Name files *.module.less or *.module.css:

css
/* example.module.less */
.container { padding: 24px; }
.title { font-size: 16px; }
tsx
import styles from './example.module.less';
<div className={styles.container} />

antd-style (CSS-in-JS):

tsx
import { createStyles } from 'antd-style';

const useStyles = createStyles(({ token, css }) => ({
  card: css`
    background: ${token.colorBgContainer};
    border-radius: ${token.borderRadiusLG}px;
  `,
}));

const { styles } = useStyles();
<div className={styles.card} />

Tailwind CSS (v4): Use directly in className:

tsx
<div className="flex items-center gap-4 p-6 rounded-lg bg-white dark:bg-[#141414]" />

Dynamic theme: Set in config/config.ts antd config:

ts
antd: {
  configProvider: {
    theme: {
      token: {
        colorPrimary: '#1890ff',
        borderRadius: 6,
      },
    },
  },
},

Use SettingDrawer in dev mode to switch themes in real-time.

💡 Three styling approaches can coexist: Tailwind for layout, CSS Modules for component styles, antd-style when consuming theme tokens.

→ See umi Styling, Umi Max antd Dynamic Theme

Testing & Debugging

Jest testing:

bash
npm test                    # Run all tests
npm run test:coverage       # With coverage report
npm run test:update         # Update snapshots

Test files go next to the component, named *.test.ts(x).

Mock data: Create files in mock/:

ts
// File: mock/user.ts
export default {
  'GET /api/currentUser': { name: 'Serati Ma', access: 'admin' },
  'POST /api/login': (req, res) => { res.end('ok'); },
};

Umi auto-registers mocks, active in dev mode.

Proxy config is in config/proxy.ts:

ts
// File: config/proxy.ts
export default {
  dev: {
    '/api/': {
      target: 'http://localhost:8080',
      changeOrigin: true,
    },
  },
};

💡 Use MOCK=none to skip mock and proxy to backend: npm run start:no-mock.

→ See umi Testing, umi Mock

FAQ

Q: How to disable Mock?
npm run start:no-mock or cross-env MOCK=none max dev

Q: How to change the primary color?
Edit colorPrimary in config/defaultSettings.ts. Use SettingDrawer for live preview in dev mode.

Q: How to add a new page?

  1. Create component in src/pages/ 2. Add route in config/routes.ts 3. Add menu translation in src/locales/ (if needed)

Q: How to add global state?
Create a file in src/models/ exporting a custom Hook, then use useModel('filename') in components.

Q: How to upgrade the project?
First, install the pro-upgrade skill into your project:

bash
npx skills add ant-design/ant-design-pro

Then run /pro-upgrade in Claude Code at the project root — AI will auto-diff the latest template and assist your upgrade (deps, config, code patterns, etc.), with conservative handling for ambiguous merges. For other AI assistants, paste the content of .claude/skills/pro-upgrade/SKILL.md to them.

Q: How to deploy?
npm run build generates dist/. Deploy to any static file server. Set publicPath for non-root deployments. npm run deploy builds and publishes to GitHub Pages automatically (pushes to gh-pages branch).

Q: How to use OpenAPI code generation?

  1. Configure openAPI in config/config.ts 2. Run npm run openapi 3. Code is auto-generated under src/services/

→ See umi FAQ

Common Tasks

Add a New Page

bash
# 1. Create the page component
#    File: src/pages/my-page/index.tsx

# 2. Register in route config
#    File: config/routes.ts
#    { path: '/my-page', name: 'myPage', icon: 'file', component: './my-page' }

# 3. Add i18n translations (for menu display)
#    File: src/locales/zh-CN/menu.ts → menu.myPage: '我的页面'
#    File: src/locales/en-US/menu.ts → menu.myPage: 'My Page'

Add Global State

bash
# 1. Create a model file (filename becomes the model key)
#    File: src/models/myModel.ts
#    Export a custom Hook: export default function useMyModel() { ... }

# 2. Use in components
#    import { useModel } from '@umijs/max';
#    const { data } = useModel('myModel');  // 'myModel' matches filename

Add a Mock API

bash
# Global mock: mock/api.ts (applies to all environments)
# Page-level mock: src/pages/my-page/_mock.ts (auto-discovered by Umi)

# Mock format:
# export default { 'GET /api/my-data': { data: [] } }

Generate API Service Code

bash
# 1. Edit OpenAPI config: config/oneapi.json
# 2. Run generation (overwrites src/services/ant-design-pro/)
npm run openapi
# 3. Never edit generated code manually — modify oneapi.json and regenerate

Switch to Simple Mode

bash
git add -A && git commit -m "chore: save before simple"  # Must commit first
npm run simple                                              # Irreversible
npm install                                                 # Update dependencies

AI Skills (Claude Code)

This project includes two built-in Claude Code Skills (.claude/skills/):

`/pro-upgrade` — Project Upgrade Assistant

Auto-upgrade to the latest Ant Design Pro version. Diffs the latest template against your project and merges framework changes while preserving business code.

bash
# In Claude Code, just run:
/pro-upgrade

What it does:

  1. Clones the latest Pro template
  2. Classifies framework vs. business files
  3. Merges dependency updates, config changes, and code pattern migrations
  4. Runs npx antd lint to catch antd-specific issues
  5. Verifies with npm run lint && npm run build

`/antd` — Ant Design CLI Helper

Query antd component APIs, debug issues, lint for deprecated usage, and assist migrations — all via @ant-design/cli with offline bundled metadata.

bash
# In Claude Code, just run:
/antd

Key commands available:

  • npx antd info <Component> — props, types, version info
  • npx antd demo <Component> <demo> — working code examples
  • npx antd lint ./src — check for deprecated/problematic usage
  • npx antd migrate <from> <to> — migration checklist between versions
  • npx antd doc <Component> — full component documentation

Installation & Updates

💡 If your project was cloned from this repo, these skills are already included — no installation needed.

To get the latest skill definitions (or add them to an existing project):

bash
npx skills add ant-design/ant-design-pro

For other AI assistants (Cursor, etc.), paste the content of .claude/skills/pro-upgrade/SKILL.md or .claude/skills/antd/SKILL.md into the assistant's context.

Constraints & Gotchas

  • src/services/ant-design-pro/ is auto-generated code. Do NOT edit manually. Modify config/oneapi.json and run npm run openapi to regenerate.
  • npm run simple is irreversible: It deletes demo pages and unused dependencies. Always commit before running.
  • .umi temp directory: src/.umi is auto-generated by Umi. Delete it and restart the dev server if you encounter unexpected behavior.
  • Biome over ESLint: This project uses Biome for linting and formatting. Do not install ESLint or Prettier plugins.
  • Commit convention: Must follow Conventional Commits (e.g., feat:, fix:, chore:).
  • npx antd lint ./src: Must pass with zero errors and warnings before committing.
  • Mock priority: mock/ directory for global mocks, src/pages/**/_mock.ts for page-level mocks. Both are auto-registered by Umi.
  • Styling priority: Tailwind (layout) > antd-style (theme tokens) > CSS Modules (component styles) > Less (legacy global styles only).
  • Path aliases: @/* → ./src/*, @@/* → ./src/.umi/*

Cheatsheet.Zh CN (`docs/cheatsheet.zh-CN.md`)

Ant Design Pro Cheatsheet

🎉 v6 新特性

  • React 19 + antd 6 + Umi Max 4:全面升级到最新技术栈,utoopack(Turbopack)构建
  • 样式重构:Less → Tailwind CSS v4 + antd-style + CSS Modules,启用 CSS 变量主题
  • AI 助手页面:基于 Ant Design X 的聊天界面示例
  • React Query:从 useRequest 迁移到 @tanstack/react-query
  • Biome:替代 ESLint + Prettier,统一 lint 和格式化
  • Cloudflare Worker 后端:演示 API 独立部署,基于 Hono 框架
  • 更多:路由预加载、骨架屏 Loading、D3 地图、Cheatsheet 速查文档、moment → dayjs、Class → 函数式组件

→ 查看完整更新日志

快速开始

创建项目:

bash
git clone --depth 1 https://github.com/ant-design/ant-design-pro.git my-project
cd my-project
npm install

项目提供两种模式:

  • 完整模式:包含所有示例页面(Dashboard、表单、列表、权限等),适合参考学习
  • 精简模式:仅保留登录页和基础布局,适合从零开发

切换精简模式:

bash
git add -A && git commit -m "chore: save before simple"  # 先提交,以便回退
npm run simple                                             # 删除示例页面和多余依赖
npm install                                                # 更新依赖

💡 建议先用完整模式熟悉项目结构,再切换精简模式开始开发。

目录结构:

text
├── config/           # 配置文件(路由、代理、主题)
│   ├── config.ts     # 主配置
│   ├── routes.ts     # 路由配置
│   ├── defaultSettings.ts  # 布局主题设置
│   └── proxy.ts      # 开发代理配置
├── mock/             # Mock 数据
├── src/
│   ├── components/   # 公共组件
│   ├── locales/      # 国际化资源
│   ├── models/       # 全局数据模型
│   ├── services/     # API 服务层
│   ├── utils/        # 工具函数
│   ├── access.ts     # 权限定义
│   └── app.tsx       # 运行时配置
├── docs/             # 项目文档
└── types/            # 类型声明

常用命令:

命令 说明
npm start 启动开发服务器(UMI_ENV=dev,带 Mock)
npm run dev 启动开发服务器(UMI_ENV=dev,无 Mock)
npm run start:no-mock 无 Mock 启动
npm run start:pre 预发布环境启动
npm run start:test 测试环境启动
npm run build 构建生产产物
npm run preview 预览已构建产物(需先 npm run build,端口 8000)
npm run preview:build 构建并本地预览(端口 8000)
npm run deploy 构建并部署到 GitHub Pages
npm run analyze 构建产物体积分析
npm run lint 代码检查(Biome + TypeScript)
npm run biome Biome 自动修复
npm test 运行测试
npm run test:coverage 测试覆盖率
npm run test:update 更新测试快照
npm run tsc 类型检查(不生成文件)
npm run i18n-remove 移除国际化(locale=zh-CN)
npm run record 录制登录场景请求数据
npm run openapi 根据 OpenAPI 生成 API 代码
npm run simple 精简模式(删除示例页面和多余依赖)

💡 UMI_ENV 用于切换环境配置,对应 config/proxy.ts 中的不同代理规则。

💡 npm run simple 会删除示例页面(dashboard、form、list 等)和多余依赖(plots 等),替换为精简路由,适合从零开始开发。建议先提交代码,以便需要时回退。

构建工具: 本项目使用 utoopack(基于 Turbopack 的新一代打包器)作为默认构建工具,通过 config/config.ts 中的 utoopack 字段配置。utoopack 兼容 Webpack 配置格式,支持 module.rules 配置自定义加载器。

→ 更多内容见 umi 入门指南、utoo 文档

路由与菜单

路由配置 位于 config/routes.ts:

ts
// File: config/routes.ts
export default [
  {
    path: '/welcome',
    name: 'welcome',     // 对应 menu.welcome 国际化 key
    icon: 'home',
    component: './Welcome',
  },
  {
    path: '/admin',
    name: 'admin',
    icon: 'crown',
    access: 'canAdmin',  // 路由级权限控制
    routes: [...],
  },
  { path: '/', redirect: '/dashboard/analysis' },
  { component: '404', path: './*' },
];

路由导航:

tsx
import { useNavigate, useParams, useLocation } from '@umijs/max';

const navigate = useNavigate();
navigate('/dashboard');        // 跳转
navigate(-1);                  // 后退

const { id } = useParams();   // 获取动态参数 /user/:id
const location = useLocation(); // 当前路由信息

菜单与权限联动: 路由配置中 access 字段控制菜单可见性,未授权路由不会出现在菜单中。

💡 name 字段自动映射为 menu.xxx 国际化 key,在 src/locales/ 中配置翻译。

→ 更多内容见 umi 路由文档、Umi Max 布局与菜单

布局

ProLayout 配置 位于 config/defaultSettings.ts:

ts
// File: config/defaultSettings.ts
export default {
  navTheme: 'light',               // 导航主题:light / dark
  colorPrimary: '#1890ff',         // 主题色
  layout: 'mix',                   // 布局模式:side / top / mix
  contentWidth: 'Fluid',           // 内容宽度:Fluid / Fixed
  fixedHeader: false,              // 固定顶部导航
  fixSiderbar: true,               // 固定侧边栏
  colorWeak: false,                // 色弱模式
  title: 'Ant Design Pro',         // 站点标题
  logo: 'https://...',             // Logo URL
  iconfontUrl: '',                 // 图标字体 URL
  token: {},                       // ProLayout token,用于细粒度样式定制
};

布局模式:

  • side — 左侧导航
  • top — 顶部导航
  • mix — 顶部 + 侧边混合导航

页面容器:

tsx
import { PageContainer } from '@ant-design/pro-components';

const Page = () => (
  <PageContainer
    header={{ title: '页面标题' }}
    content="页面描述"
  >
    {/* 页面内容 */}
  </PageContainer>
);

自定义区域: 右上角 src/components/RightContent,底部 src/components/Footer。

→ 更多内容见 Umi Max 布局与菜单

数据流

useModel — 轻量全局状态: 在 src/models/ 下创建文件即自动注册:

ts
// File: src/models/counter.ts
import { useState } from 'react';

export default function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(c => c + 1);
  return { count, increment };
}
tsx
// 任意组件中使用
import { useModel } from '@umijs/max';

const { count, increment } = useModel('counter');

useRequest — 数据请求:

tsx
import { useRequest } from '@umijs/max';

const { data, loading, error } = useRequest(getUserInfo);

React Query — 服务端状态管理:

tsx
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

// 查询
const { data, isLoading } = useQuery({
  queryKey: ['user', id],
  queryFn: () => getUser(id),
});

// 变更
const mutation = useMutation({
  mutationFn: updateUser,
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['user'] });
  },
});

初始状态 — getInitialState: 在 src/app.tsx 中定义,全局可访问:

tsx
// File: src/app.tsx
export async function getInitialState() {
  const currentUser = await fetchUserInfo();
  return { currentUser };
}

// 组件中使用
import { useModel } from '@umijs/max';
const { initialState } = useModel('@@initialState');

💡 getInitialState 在应用启动时执行一次,适合获取全局信息(如用户身份、权限)。

→ 更多内容见 Umi Max 数据流

请求

请求配置 位于 src/app.tsx:

ts
// File: src/app.tsx
export const request: RequestConfig = {
  baseURL: 'https://api.example.com',
  timeout: 10000,
  requestInterceptors: [],   // 请求拦截器
  responseInterceptors: [],  // 响应拦截器
};

错误处理 位于 src/requestErrorConfig.ts,可自定义错误码映射和提示逻辑。

使用请求:

tsx
import { request } from '@umijs/max';

// GET
const data = await request('/api/users', { params: { page: 1 } });

// POST
await request('/api/users', { method: 'POST', data: { name: 'test' } });

OpenAPI 代码生成:

bash
npm run openapi

根据 config/oneapi.json 自动生成 src/services/ 下的 API 调用代码。

💡 生成后的代码直接用 import { request } from '@umijs/max' 发起请求,无需手动封装。

→ 更多内容见 Umi Max 请求

权限

定义权限 在 src/access.ts:

ts
// File: src/access.ts
export default function access(initialState: { currentUser?: API.CurrentUser }) {
  const { currentUser } = initialState;
  return {
    canAdmin: currentUser?.access === 'admin',
    canUser: !!currentUser,
  };
}

路由级权限: 在路由配置中添加 access 字段:

ts
{ path: '/admin', access: 'canAdmin' }

组件级权限:

tsx
import { Access, useAccess } from '@umijs/max';

// 声明式
<Access accessible={access.canAdmin}>
  <AdminPanel />
</Access>

// 命令式
const access = useAccess();
if (access.canAdmin) { /* ... */ }

→ 更多内容见 Umi Max 权限

国际化

配置 在 config/config.ts:

ts
locale: {
  default: 'zh-CN',
  antd: true,         // 同步 antd 组件语言
  baseNavigator: true, // 跟随浏览器语言
},

文件结构:

text
src/locales/
├── zh-CN.ts        # 中文入口
├── zh-CN/
│   ├── menu.ts     # 菜单翻译
│   ├── pages.ts    # 页面翻译
│   └── ...
├── en-US.ts        # 英文入口
└── en-US/
    └── ...

使用方式:

tsx
import { useIntl, FormattedMessage } from '@umijs/max';

// Hook 方式
const intl = useIntl();
intl.formatMessage({ id: 'menu.welcome' });

// 组件方式
<FormattedMessage id="menu.welcome" />

切换语言:

tsx
import { setLocale } from '@umijs/max';
setLocale('en-US', false);  // false = 不刷新页面

→ 更多内容见 Umi Max 国际化

样式

CSS Modules: 文件命名为 *.module.less 或 *.module.css:

css
/* example.module.less */
.container { padding: 24px; }
.title { font-size: 16px; }
tsx
import styles from './example.module.less';
<div className={styles.container} />

antd-style(CSS-in-JS):

tsx
import { createStyles } from 'antd-style';

const useStyles = createStyles(({ token, css }) => ({
  card: css`
    background: ${token.colorBgContainer};
    border-radius: ${token.borderRadiusLG}px;
  `,
}));

const { styles } = useStyles();
<div className={styles.card} />

Tailwind CSS(v4): 直接在 className 中使用:

tsx
<div className="flex items-center gap-4 p-6 rounded-lg bg-white dark:bg-[#141414]" />

动态主题: 在 config/config.ts 的 antd 配置中设置:

ts
antd: {
  configProvider: {
    theme: {
      token: {
        colorPrimary: '#1890ff',
        borderRadius: 6,
      },
    },
  },
},

开发环境可通过右下角 SettingDrawer 实时切换主题。

💡 三种样式方案可以共存:Tailwind 适合布局、CSS Modules 适合组件样式、antd-style 适合需要消费主题 token 的场景。

→ 更多内容见 umi 样式文档、Umi Max antd 动态主题

测试 & 调试

Jest 测试:

bash
npm test                    # 运行所有测试
npm run test:coverage       # 带覆盖率报告
npm run test:update         # 更新快照

测试文件放在对应组件目录下,命名为 *.test.ts(x)。

Mock 数据: 在 mock/ 目录下创建文件:

ts
// File: mock/user.ts
export default {
  'GET /api/currentUser': { name: 'Serati Ma', access: 'admin' },
  'POST /api/login': (req, res) => { res.end('ok'); },
};

Umi 自动注册 mock,开发模式下生效。

代理配置 位于 config/proxy.ts:

ts
// File: config/proxy.ts
export default {
  dev: {
    '/api/': {
      target: 'http://localhost:8080',
      changeOrigin: true,
    },
  },
};

💡 用 MOCK=none 启动可跳过 Mock,直接代理到后端:npm run start:no-mock。

→ 更多内容见 umi 测试、umi Mock

FAQ

Q: 如何关闭 Mock?
npm run start:no-mock 或 cross-env MOCK=none max dev

Q: 如何修改主题色?
修改 config/defaultSettings.ts 的 colorPrimary,开发时可用 SettingDrawer 实时调整。

Q: 如何添加新页面?

  1. 在 src/pages/ 下创建组件 2. 在 config/routes.ts 添加路由 3. 在 src/locales/ 添加菜单翻译(如需)

Q: 如何添加全局状态?
在 src/models/ 下创建文件,导出自定义 Hook,组件中通过 useModel('文件名') 使用。

Q: 如何升级项目?
先将 pro-upgrade skill 安装到项目中:

bash
npx skills add ant-design/ant-design-pro

然后在项目根目录用 Claude Code 运行 /pro-upgrade,AI 会自动对比最新模板并辅助完成升级(依赖、配置、代码模式等),遇到冲突时会保守处理并询问确认。如使用其他 AI 助手,可将 .claude/skills/pro-upgrade/SKILL.md 中的内容提供给它。

Q: 如何部署?
npm run build 生成 dist/ 目录,部署到任意静态服务器。配置 publicPath 处理非根目录部署。npm run deploy 会自动构建并发布到 GitHub Pages(推送到 gh-pages 分支)。

Q: 如何使用 OpenAPI 代码生成?

  1. 在 config/config.ts 配置 openAPI 2. 运行 npm run openapi 3. 自动生成 src/services/ 下的代码

→ 更多内容见 umi FAQ

常见任务

添加新页面

bash
# 1. 创建页面组件
#    文件路径:src/pages/my-page/index.tsx

# 2. 在路由配置中注册
#    文件路径:config/routes.ts
#    { path: '/my-page', name: 'myPage', icon: 'file', component: './my-page' }

# 3. 添加国际化翻译(如需菜单显示)
#    文件路径:src/locales/zh-CN/menu.ts → menu.myPage: '我的页面'
#    文件路径:src/locales/en-US/menu.ts → menu.myPage: 'My Page'

添加全局状态

bash
# 1. 创建 model 文件(文件名即 model key)
#    文件路径:src/models/myModel.ts
#    导出自定义 Hook:export default function useMyModel() { ... }

# 2. 在组件中使用
#    import { useModel } from '@umijs/max';
#    const { data } = useModel('myModel');  // 'myModel' 对应文件名

添加 Mock 接口

bash
# 全局 Mock:mock/api.ts(匹配所有环境)
# 页面级 Mock:src/pages/my-page/_mock.ts(Umi 自动发现)

# Mock 格式:
# export default { 'GET /api/my-data': { data: [] } }

生成 API 服务代码

bash
# 1. 编辑 OpenAPI 配置:config/oneapi.json
# 2. 运行生成命令(覆盖 src/services/ant-design-pro/)
npm run openapi
# 3. 不要手动编辑生成代码,改 oneapi.json 重新生成

切换到精简模式

bash
git add -A && git commit -m "chore: save before simple"  # 必须先提交
npm run simple                                              # 不可逆操作
npm install                                                 # 更新依赖

AI Skills(Claude Code)

本项目内置两个 Claude Code Skills(位于 .claude/skills/):

`/pro-upgrade` — 项目升级助手

自动升级到最新 Ant Design Pro 版本。对比最新模板差异,合并框架变更并保留业务代码。

bash
# 在 Claude Code 中直接运行:
/pro-upgrade

执行流程:

  1. 克隆最新 Pro 模板
  2. 将文件分类为框架文件和业务文件
  3. 合并依赖更新、配置变更和代码模式迁移
  4. 运行 npx antd lint 检查 antd 相关问题
  5. 通过 npm run lint && npm run build 验证

`/antd` — Ant Design CLI 助手

查询 antd 组件 API、调试问题、检查废弃用法、辅助版本迁移 — 基于 @ant-design/cli,离线元数据,无需网络。

bash
# 在 Claude Code 中直接运行:
/antd

常用命令:

  • npx antd info <Component> — props、类型、版本信息
  • npx antd demo <Component> <demo> — 可运行的代码示例
  • npx antd lint ./src — 检查废弃或有问题的用法
  • npx antd migrate <from> <to> — 版本迁移清单
  • npx antd doc <Component> — 完整组件文档

安装与更新

💡 如果你的项目是从本仓库克隆的,这些 skill 已经内置,无需额外安装。

获取最新 skill 定义(或将其添加到已有项目):

bash
npx skills add ant-design/ant-design-pro

如使用其他 AI 助手(Cursor 等),可将 .claude/skills/pro-upgrade/SKILL.md 或 .claude/skills/antd/SKILL.md 的内容提供给它。

注意事项

  • src/services/ant-design-pro/ 为自动生成代码,禁止手动编辑。修改 config/oneapi.json 后执行 npm run openapi 重新生成
  • npm run simple 不可逆:会删除示例页面和多余依赖,执行前务必提交代码
  • .umi 临时目录:src/.umi 由 Umi 自动生成,遇到异常可删除后重启开发服务器
  • Biome 代替 ESLint:项目使用 Biome 进行 lint 和格式化,不要安装 ESLint 或 Prettier 插件
  • Commit 规范:必须遵循 Conventional Commits,如 feat:, fix:, chore: 等
  • npx antd lint ./src:提交前必须零错误零警告
  • Mock 优先级:mock/ 目录为全局 Mock,src/pages/**/_mock.ts 为页面级 Mock,两者都会被 Umi 自动注册
  • 样式优先级:Tailwind(布局)> antd-style(主题 token)> CSS Modules(组件样式)> Less(仅遗留全局样式)
  • 路径别名:@/* → ./src/*,@@/* → ./src/.umi/*

Roadmap V6.1.0 Release Plan (`docs/roadmap/v6.1.0-release-plan.md`)

Ant Design Pro v6.1.0 Release Plan

Date: 2026-06-01
Status: Draft
Approach: Layered progression — cleanup first, then engineering, then upgrades

Overview

v6.1.0 is a quality + upgrade release focusing on test infrastructure, bug fixes, legacy cleanup, and dependency alignment. Breaking changes are allowed where justified with migration notes.

Layer 1: Cleanup & Bug Fixes

1.2 Clean up `ant-legacy-form-item` CSS class references

antd v6 removed these legacy class names. Three files still reference them:

  • src/components/StandardFormRow/index.style.ts (8 references)
  • src/pages/form/advanced-form/style.style.ts (1 reference)
  • src/pages/account/settings/components/index.style.ts (1 reference)

Action: Replace .ant-legacy-form-item selectors with current antd v6 equivalents (.ant-form-item). Verify visual parity after changes.

1.3 Clean up typings.d.ts legacy module declarations

src/typings.d.ts declares modules for slash2 and omit.js — v5-era dependencies no longer in use.

Action: Grep for actual imports. If none found, remove the declarations.

1.4 Bug fixes

# Issue Description Approach
1 #11772 valtio undefined error Trace dependency chain; fix initialization or remove unused valtio import
2 #11764 OpenAPI link text visible in collapsed sidebar CSS fix to hide text or truncate when sidebar is collapsed
3 #11747 Windows 11 "Can't resolve 'tailwindcss'" Investigate path resolution; likely needs module resolution config fix
4 #11575 OpenAPI generated file first-letter case inconsistency Review openapi config camel2Line/naming options; add normalization
5 #11286 Language switcher cannot be disabled in non-mix layouts Fix disableLocal prop propagation in layout config
6 #11597 Mask layer bug with pagination and sidebar z-index / overlay stacking fix

1.5 Clean up request interceptor demo placeholder

src/requestErrorConfig.ts appends ?token=123 to every request URL as a demo artifact.

Action: Replace with commented example or conditional (dev-only) guard. Do not remove the pattern entirely — it serves as a reference for token attachment.

Layer 2: Testing & Engineering

2.1 Migrate Jest → Vitest (#11742)

Rationale: Vitest offers native ESM, instant HMR, and Vite-native config. Jest startup is slow and ESM support is fragile.

Steps:

  1. Add vitest and @vitest/coverage-v8 dependencies
  2. Create vitest.config.ts using Umi plugin compatibility
  3. Migrate tests/ setup files (setupTests.jsx, __mocks__/)
  4. Migrate src/pages/user/login/login.test.tsx → Vitest syntax
  5. Update package.json scripts: test, test:coverage, test:ui
  6. Remove Jest dependencies: jest, @testing-library/jest-dom, related config
  7. Verify CI pipeline

Breaking change: Test authoring API changes (minimal — Vitest is Jest-compatible).

2.2 Expand test coverage

Current: 1 test file, 2 test cases, ~1% file coverage.

Priority test targets:

Target File What to test
ProTable page src/pages/list/table-list/index.tsx Data loading, search, pagination, CRUD operations
Dashboard src/pages/dashboard/analysis/index.tsx Chart rendering, layout, chart data flow
Basic form src/pages/form/basic-form/index.tsx Form validation, submission, field interactions
Auth flow src/access.ts, src/app.tsx canAdmin logic, getInitialState 401 redirect
Request interceptor src/requestErrorConfig.ts Error handling paths, 401 redirect, token attachment

Coverage target: Core pages 50%+, overall 20%+.

2.3 CI pipeline optimization

  • Enable GitHub Actions cache for node_modules and build output
  • Parallelize PR checks: lint | typecheck | test (instead of sequential)
  • Evaluate Codecov upload — remove if coverage data remains below actionable threshold

2.4 Code quality enforcement

  • Add npx antd lint ./src to CI pipeline (currently only enforced manually)
  • Tighten Biome rules: audit warnings and elevate to errors where appropriate

Layer 3: Dependency Upgrades

3.1 Core dependencies

Package From To Risk
antd ^6.4.3 6.x latest Low
@ant-design/pro-components ^3.1.12-0 3.x stable Low
@ant-design/x ^2.7.0 2.x latest Low
@ant-design/x-markdown ^2.7.0 2.x latest Low
@ant-design/x-sdk ^2.7.0 2.x latest Low
@umijs/max ^4.6.51 4.x latest Medium — check breaking notes
React / React DOM ^19.2.5 Stay (React 20 not released) —

3.2 Toolchain dependencies

Package From To
TypeScript ^6.0.3 6.x latest
Biome ^2.4.13 2.x latest
Tailwind CSS ^4.2.4 4.x latest
Express (mock) ^5.2.1 5.x latest
@tanstack/react-query ^5.100.6 5.x latest
d3 ^7.9.0 7.x latest or evaluate alternatives

3.3 Evaluation items (investigate before upgrading)

  • Node.js 22: Currently requires >= 20. Assess whether raising to >= 22 is warranted.
  • utoopack: Check for significant updates or breaking changes in the build toolchain.
  • @tanstack/react-query v6: If released, evaluate migration path.

3.4 Post-upgrade validation checklist

  • npm run lint passes (Biome + tsc)
  • npx antd lint ./src passes
  • npm run build succeeds
  • All tests pass
  • npm start dev server works
  • Visual spot-check of key pages (login, dashboard, table-list, forms)
  • Update CLAUDE.md if version requirements change

Risk Assessment

Risk Likelihood Impact Mitigation
Umi Max upgrade breaks build Medium High Pin version; test in CI before merge
Vitest + Umi plugin compatibility Medium Medium Research existing Umi + Vitest integrations; may need adapter
Windows compatibility regression Low Medium Test on Windows or add Windows CI
antd v6 minor API changes Low Low Review antd changelog; run npx antd lint
Test coverage effort exceeds estimate Medium Low Prioritize core pages; defer edge cases

Execution Order

text
Layer 1 (cleanup + bugs) → Layer 2 (testing) → Layer 3 (upgrades)

Each layer produces a shippable state. If time constrains, lower layers deliver more value per effort.

Within each layer, items can be parallelized across contributors.


Roadmap V6.1.0 Upgrade Evaluation (`docs/roadmap/v6.1.0-upgrade-evaluation.md`)

v6.1.0 升级可行性评估(#11829)

评估时间:2026-06
关联:v6.1.0 Release Tracking #11813

本文档评估三个升级项的可行性与影响范围,每项给出明确结论与是否纳入本版本的建议。


1. Node.js 22 最低版本

现状

  • package.json engines:node: ">=20.0.0"
  • CI(ci.yml / coverage.yml):仅运行 Node 20
  • 本地开发环境:Node 22.22.0

调研

  • Node.js 20 (Iron) 已于 2026-03 进入 EOL,不再接收安全更新,不应用于生产环境。
  • Node.js 22 (Jod) 是当前 Active LTS,维护周期覆盖整个 v6.1.0 生命周期。
  • 生态兼容性:vitest 已要求 ^18 || ^20 || >=22(明确跳过 21),@biomejs/biome 要求 >=14,其余工具链对 Node 22 均无障碍。
  • 升级成本低:Pro 自身代码不依赖 Node 20 特有行为,仅需调整 engines 与 CI 矩阵。

结论:✅ 建议本版本升级到 Node 22

理由:Node 20 已 EOL,继续以其为最低版本存在安全风险。Node 22 是当前 LTS 且生态完全就绪。

落地动作(独立 PR):

  • package.json engines 改为 node: ">=22.0.0"
  • CI 工作流 node-version / node_version 矩阵改为 22
  • 更新 CLAUDE.md 中 Node ≥ 20 的描述

2. utoopack(@utoo/pack)

现状

  • @utoo/pack 不是项目直接依赖,而是 @umijs/max 的传递依赖:
    text
    @umijs/max → umi → @umijs/preset-umi → @umijs/bundler-utoopack → @utoo/[email protected]
  • 已安装版本 1.4.3,npm latest 为 1.4.9
  • 项目仅在 config/config.ts 中通过 utoopack: {} 配置选项和 require('@utoo/pack/package.json').version 读取版本号

调研

  • 由于 @utoo/pack 的版本由 @umijs/max 锁定,不应在本项目中单独升级——单独提升会与 Umi 的 bundler 版本产生不一致,且会在 @umijs/max 下次升级时被覆盖。
  • 正确的升级路径是跟随 @umijs/max 升级(见 #11827),由 Umi 团队保证 bundler 与框架的兼容性。

结论:⏭️ 不单独升级,跟随 @umijs/max

理由:传递依赖应由上游框架管理。当前 1.4.3 随 @umijs/[email protected] 工作正常,构建验证通过。


3. @tanstack/react-query v6

现状

  • 当前版本:5.100.x(#11828 已升至 5.100.14)
  • 通过 @umijs/max 的 reactQuery 插件集成(config/config.ts 中 reactQuery: {})

调研

  • npm dist-tags 显示 react-query 尚无 v6 发布:
    text
    latest: 5.100.14   (无 v6 / next-major tag)
  • v5 仍在活跃维护,持续发布小版本。

结论:⏭️ v6 未发布,继续跟随 v5 最新版

理由:v6 不存在,无迁移路径可言。保持 v5 最新(5.100.14)即可。待 v6 发布后再单独评估迁移成本(届时需关注 Umi reactQuery 插件的适配)。


汇总

评估项 结论 是否本版本执行
Node.js 22 最低版本 ✅ 建议升级(Node 20 已 EOL) 是,独立 PR
utoopack ⏭️ 跟随 @umijs/max,不单独升级 否
@tanstack/react-query v6 ⏭️ v6 未发布,跟随 v5 否

--- METRICS ---