返回

使用 create-react-app 创建并自定义一个带有 Ant Design 的 React 项目

前端

当然,我很乐意为您撰写一篇关于如何在 create-react-app 中使用 antd@4.x 的文章。

使用 create-react-app 创建 React 项目

  1. 安装 create-react-app。
npm install -g create-react-app
  1. 创建一个新的 React 项目。
create-react-app my-app
  1. 进入项目目录。
cd my-app

安装 Ant Design

  1. 安装 Ant Design。
npm install antd
  1. src/index.js 中导入 Ant Design。
import 'antd/dist/antd.css';
  1. src/App.js 中使用 Ant Design 组件。
import { Button } from 'antd';

const App = () => {
  return (
    <div>
      <Button type="primary">Button</Button>
    </div>
  );
};

export default App;

自定义主题

  1. 安装 craco。
npm install craco --save-dev
  1. 在项目根目录创建一个 craco.config.js 文件。
module.exports = {
  webpack: {
    configure: {
      resolve: {
        alias: {
          'antd/lib': path.resolve(__dirname, 'node_modules/antd/lib'),
        },
      },
    },
  },
};
  1. package.json 中修改 scripts 属性。
{
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test"
  }
}
  1. src/theme.less 中定义主题变量。
@primary-color: #40a9ff;
  1. src/index.js 中导入主题变量。
import './theme.less';
  1. 重新启动项目。
npm start

您的项目现在就可以使用自定义主题了。

总结

在本文中,我们介绍了如何在 create-react-app 中使用 Ant Design,以及如何自定义主题。希望这篇文章对您有所帮助。