logoAnt Design

⌘ K
  • 设计
  • 研发
  • 组件
  • 博客
  • 资源
5.3.3
  • Ant Design of React
  • 快速上手
  • 项目实战
  • 在 create-react-app 中使用
  • 在 TypeScript 中使用
  • 样式兼容
  • 定制主题
  • 使用自定义日期库
  • 从 v4 到 v5
  • 社区精选组件
  • 国际化
  • FAQ
  • 贡献指南
  • 更新日志
安装和初始化
引入 antd
高级配置
自定义主题
其他方案

在 TypeScript 中使用

在 create-react-app 中使用样式兼容

相关资源

Ant Design Charts
Ant Design Pro
Ant Design Pro Components
Ant Design Mobile
Ant Design Mini
Ant Design Landing-首页模板集
Scaffolds-脚手架市场
Umi-React 应用开发框架
dumi-组件/文档研发工具
qiankun-微前端框架
ahooks-React Hooks 库
Ant Motion-设计动效
国内镜像站点 🇨🇳

社区

Awesome Ant Design
Medium
Twitter
yuqueAnt Design 语雀专栏
Ant Design 知乎专栏
体验科技专栏
seeconfSEE Conf-蚂蚁体验科技大会
加入我们

帮助

GitHub
更新日志
常见问题
报告 Bug
议题
讨论区
StackOverflow
SegmentFault

Ant XTech更多产品

yuque语雀-构建你的数字花园
AntVAntV-数据可视化解决方案
EggEgg-企业级 Node.js 框架
kitchenKitchen-Sketch 工具集
xtech蚂蚁体验科技
主题编辑器
Made with ❤ by
蚂蚁集团和 Ant Design 开源社区

使用 create-react-app 一步步地创建一个 TypeScript 项目,并引入 antd。

antd 基于最新稳定版本的 TypeScript(>=4.0.0),请确保项目中使用匹配的版本。


安装和初始化

请确保电脑上已经安装了最新版的 yarn 或者 npm。

使用 yarn 创建 cra-template-typescript 项目。

$ yarn create react-app antd-demo-ts --template typescript

如果你使用的是 npm(接下来我们都会用 yarn 作为例子,如果你习惯用 npm 也没问题)。

$ npx create-react-app antd-demo-ts --template typescript

然后我们进入项目并启动。

$ cd antd-demo-ts
$ yarn start

此时浏览器会访问 http://localhost:3000/ ,看到 Welcome to React 的界面就算成功了。

引入 antd

$ yarn add antd

修改 src/App.tsx,引入 antd 的按钮组件。

import React from 'react';
import type { FC } from 'react';
import { Button } from 'antd';
import 'antd/dist/reset.css';
import './App.css';
const App: FC = () => (
<div className="App">
<Button type="primary">Button</Button>
</div>
);
export default App;

重新启动 yarn start,现在你应该能看到页面上已经有了 antd 的蓝色按钮组件,接下来就可以继续选用其他组件开发应用了。其他开发流程你可以参考 create-react-app 的官方文档。

antd 使用 TypeScript 书写并提供了完整的定义,你可以享受组件属性输入建议和定义检查的功能。

注意不要安装 @types/antd。

高级配置

这个例子在实际开发中还有一些优化的空间,比如无法进行主题配置。

此时我们需要对 create-react-app 的默认配置进行自定义,这里我们使用 craco (一个对 create-react-app 进行自定义配置的社区解决方案)。

现在我们安装 craco 并修改 package.json 里的 scripts 属性。

$ yarn add @craco/craco
/* package.json */
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
}

然后在项目根目录创建一个 craco.config.js 用于修改默认配置。

/* craco.config.js */
module.exports = {
// ...
};

自定义主题

参考 配置主题,通过 ConfigProvider 进行主题配置:

import React from 'react';
import { ConfigProvider } from 'antd';
export default () => (
<ConfigProvider
theme={{
token: {
colorPrimary: '#00b96b',
},
}}
>
<MyApp />
</ConfigProvider>
);

其他方案

如果你已经按照 在 create-react-app 中使用 初始化了环境,可以参考官方文档里的 Adding TypeScript 配置 TypeScript 开发环境。

  • Create React apps (with Typescript and antd) with no build configuration
  • react-app-rewire-typescript
  • ts-import-plugin
  • Migrating from create-react-app-typescript to Create React App