将 Create-React-App 与 antd 结合使用

Use Create-React-App with antd

我尝试使用 antd with create react app

我在项目中使用

安装了antd
yarn add antd

使用antd的按钮组件添加了一个按钮

import React, { Component } from 'react';
import Button from 'antd/lib/button';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}

export default App;

不过,按钮没有正确呈现。检查元素时,我发现正在应用 antd 类 。只是css没有加载

我不得不在 src/App.css.

的顶部添加 antd/dist/antd.css
@import '~antd/dist/antd.css';

.App {
  text-align: center;
}

我从 antd's official docs for using with Create React App

中了解到这一点

所以需要的所有步骤都是安装antd

yarn add antd

使用antd的组件

import React, { Component } from 'react';
import Button from 'antd/lib/button';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}

export default App;

并在 css 主文件中导入 antdcss (src/App.css)

尽管经过验证的答案有效,您可以通过仅导入所需的 CSS 来最小化构建 中 CSS 包的大小如下

import Button from 'antd/lib/button';
import 'antd/lib/button/style/css'; // importing only the required CSS

更新

最近注意到即使按照上面提到的方式导入 antd 组件(删除文本)它仍然会在构建中添加不必要的 JS,

我什至在 ant design docs issue still the same ( still adds unnecessary JS in to the build ). So I opened an issue on the antd repo : https://github.com/ant-design/ant-design/issues/13274 中尝试过 react-app-rewired

更新二:

请看一下:https://github.com/ant-design/ant-design/issues/12011

在项目中安装 antd 后,您可以将按钮导入为

从 'antd' 导入 {Button};

首先通过 npm i less-loader 在 npm 上安装 less-loader, 然后在 index.js 目录下创建一个 index.less 文件夹。 将其粘贴到 index.less -> @import "~antd/dist/antd.dark.less"; 之后将这个 .less 文件导入到您的 index.js 并玩得开心 :) 你可以找到一些其他的方法here

你也可以使用 craco(create react app config override) 但它更复杂。