安装,各种装先
$ create-react-app antd-demo && cd antd-demo
...
$ yarn add antd
...
$ yarn add react-app-rewired customize-cra -D
...
$ yarn add less less-loader babel-plugin-import -D
...
done
修改 package.json
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
}
根目录新建文件 config-overrides.js
const { override, fixBabelImports, addLessLoader } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true,
}),
addLessLoader({
javascriptEnabled: true,
// modifyVars: { '@primary-color': '#1DA57A' }, # 这里不注释掉,那你的无法修改主题色primary-color 这里很坑的 要注意!
}),
);
使用 less 定义样式并修改主题
src/App.js
import React, { Component, Fragment } from 'react'
import { Button } from 'antd';
import './style.less' //引入less文件
// Components
class App extends Component {
render(){
return(
<Fragment>
<Button type="primary">Primary</Button>
<Button>Default</Button>
<Button type="dashed">Dashed</Button>
<Button type="danger">Danger</Button>
</Fragment>
)
}
}
export default App
新建一个less文件src/style.less
@import "~antd/dist/antd.less"; //引入官方样式的less文件
@primary-color: deeppink; //修改主题
注意,这种方式已经载入了所有组件的样式,不需要也无法和按需加载插件 babel-plugin-import 的 style 属性一起使用。
因此需要把 config-overrides.js
修改成这样👇
const { override, fixBabelImports, addLessLoader } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
// style: true, # 这里不注释掉就无法使用less修改主题,这里的功能是样式按需加载
}),
addLessLoader({
javascriptEnabled: true,
// modifyVars: { '@primary-color': '#1DA57A' },
}),
);