如何安装antd react
安装 Ant Design (antd) 到 React 项目
确保已创建 React 项目,若未创建可通过以下命令初始化:
npx create-react-app my-app
cd my-app
通过 npm 或 yarn 安装 antd:
npm install antd
# 或
yarn add antd
引入 Ant Design 样式
在项目的入口文件(如 src/index.js 或 src/App.js)中引入全局样式:
import 'antd/dist/antd.css';
使用 Ant Design 组件
在 React 组件中直接导入需要的组件:
import { Button } from 'antd';
function App() {
return <Button type="primary">Primary Button</Button>;
}
按需加载优化(可选)
使用 babel-plugin-import 减少打包体积。安装插件:
npm install babel-plugin-import --save-dev
# 或
yarn add babel-plugin-import --dev
在 babel.config.js 或 .babelrc 中配置:
{
"plugins": [
["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }]
]
}
自定义主题(可选)
通过 craco 或 react-app-rewired 修改默认主题变量。以 craco 为例:
安装依赖:
npm install @craco/craco craco-less --save
创建 craco.config.js:
const CracoLessPlugin = require('craco-less');
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
},
},
},
},
],
};
修改 package.json 中的脚本:
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
}





