简体   繁体   中英

Use Create-React-App with antd

I tried to use antd with create react app .

I installed antd in project using

yarn add antd

Added a button using antd's button component

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;

Still, button did not rendering correctly. When inspecting the element, I find that antd classes are being applied. It's just that css is not loaded.

I had to add antd/dist/antd.css at the top of src/App.css.

@import '~antd/dist/antd.css';

.App {
  text-align: center;
}

I figured out this from antd's official docs for using with Create React App

So all the steps required are to install antd

yarn add antd

Use a component from 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;

And import antdcss in main css file (src/App.css)

Although verified answer works, you could minimize the size of the CSS bundle in the build by only importing required CSS as follows.

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

Update

Recently noticed even importing antd components according to above mentioned way(strike through text) it still adds unnecessary JS in to the build,

I even tried react-app-rewired in 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

Update 2:

Please take a look at : https://github.com/ant-design/ant-design/issues/12011

After installing antd in your project you can import button as

import {Button} from 'antd';

First install less-loader on npm via npm i less-loader , then create a index.less folder on the index.js directory. paste this on index.less -> @import "~antd/dist/antd.dark.less"; After that import this .less file to your index.js and have fun :) You can find some other methods here

You can also use craco(create react app config override) but its more complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM