React - Ant Design4.x版本安装使用,并按需引入和自定义主题

本文详细介绍了如何在React项目中使用Ant Design 4.x版本,包括安装、基本使用、配置craco以自定义主题,以及通过babel-plugin-import实现按需加载组件。步骤包括安装antd、引入样式、配置craco和less,以及设置自定义主题颜色。此外,还演示了如何配置按需加载以优化性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ant Design官网:https://4x.ant.design/docs/react/use-with-create-react-app

一. 安装使用 antd

  1. 安装 antd
    yarn add antd@4.24.3

  2. 修改 src/App.css 文件,引入antd/dist/antd.css

    @import '~antd/dist/antd.css';
    
  3. 修改 src/App.js 文件,引入 App.css 样式文件,并使用 andt 组件。

    import { Button } from 'antd';
    import './App.css';
    
    function App() {
      return (
        <div className="App">
          <Button type="primary">Button</Button>
        </div>
      );
    }
    
    export default App;
    
  4. 页面正常显示 antd 的蓝色按钮组件,说明已经把 antd 组件成功运行起来了。

二.antd 高级配置

安装 craco,对 create-react-app 的默认配置进行自定义

  1. 安装 craco
    yarn add @craco/craco

  2. 修改 package.json 里的 scripts 属性
    在这里插入图片描述

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

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

自定义主题

定制主题: https://4x.ant.design/docs/react/customize-theme-cn

  1. 安装 craco-less
    yarn add craco-less

  2. 修改craco.config.js 文件,配置 lessOptions

    const CracoLessPlugin = require("craco-less");
    
    module.exports = {
      plugins: [
        {
          plugin: CracoLessPlugin,
          options: {
            lessLoaderOptions: {
              lessOptions: {
                // 自定义less变量
                modifyVars: { "@primary-color": "#1DA57A" },
                javascriptEnabled: true,
              },
            },
          },
        },
      ],
    };
    
  3. src/App.css 文件修改为 src/App.less,并修改样式引用为 @import '~antd/dist/antd.less';
    在这里插入图片描述

  4. 修改 src/App.js,引用文件为 src/App.less
    在这里插入图片描述

  5. yarn start 重启项目访问页面,如果看到一个绿色的按钮就说明配置成功了。

安装 babel-plugin-import ,按需加载组件代码和样式

  1. 安装 babel-plugin-import
    yarn add babel-plugin-import

  2. 修改craco.config.js 文件,配置 babel-plugin-import

    const CracoLessPlugin = require("craco-less");
    
    module.exports = {
      plugins: [
        {
          plugin: CracoLessPlugin,
          options: {
            lessLoaderOptions: {
              lessOptions: {
                // 自定义less变量
                modifyVars: { "@primary-color": "#1DA57A" },
                javascriptEnabled: true,
              },
            },
          },
        },
      ],
      // 配置babel-plugin-import按需引用
      babel: {
        plugins: [
          ["import", { libraryName: "antd", libraryDirectory: "es", style: true }],
          ["@babel/plugin-proposal-decorators", { legacy: true }],
        ],
      },
    };
    
  3. 移除前面在 src/App.less 里全量添加的@import '~antd/dist/antd.less';yarn start 重启项目访问页面,antd 组件的 jscss 代码都会按需加载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值