Install dependencies
// Install create-react-app globally, as it will be used frequently
yarn global add create-react-app
Copy the code
Create the project and install the dependencies
yarn create react-app react-antd
cd react-antd
// Install antD in the react-antd project
yarn add antd -S
Copy the code
Customizes the default create-react-app configuration
Craco (a community solution for customizations of create-React-app) is recommended for [email protected] when customizations of create-React-app are required.
Now let’s install Craco and change the scripts property in package.json.
yarn add @craco/craco
Copy the code
/* package.json */
"scripts": {-"start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",}Copy the code
Then create a craco.config.js file in the project root directory to modify the default configuration.
/* craco.config.js */
module.exports = {
// ...
};
Copy the code
Customize theme colors and use less in your project
To customize a theme, you need to use the less variable override function similar to that provided by less-loader. We can introduce craco-less to help load less styles and modify variables.
First change the SRC/app.css file to SRC/app.less and then change the style reference to less.
/* src/App.js */
- import './App.css';
+ import './App.less';
Copy the code
/* src/App.less */- the @import '~antd/dist/antd.css';
+ @import '~antd/dist/antd.less';
Copy the code
Then install craco-less and modify the craco.config.js file as follows.
yarn add craco-less
Copy the code
const CracoLessPlugin = require('craco-less');
module.exports = {
plugins: [{plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,},},},},],};Copy the code
ModifyVars of less-Loader is used for theme configuration. For variables and other configuration methods refer to the Configuration Theme documentation. After the modification, restart YARN Start. If a green button is displayed, the configuration is successful.
Antd has built in dark theme and compact theme, you can refer to using dark theme and compact theme access.
Similarly, you can customize the create-react-app Webpack configuration using react-app-rewired and customize-cra.
Import antD component styles as needed
In real projects, loading on demand is often used to reduce the size of the package. The steps are as follows: Install the dependency babel-plugin-import
yarn add babel-plugin-import
Copy the code
Then add it to craco.config.js
babel: {
plugins: [["import",
{
"libraryName": "antd"."libraryDirectory": "es"."style": true // Set to true to less}}]].Copy the code
When the configuration is complete, there is no need to import additional style files when referencing components. Babel will automatically import styles for you on demand