1、安装插件
npm install antd-theme-generator
2、src文件夹下添加styles/index.less+styles/variables.less
根目录新建color.js
const path = require('path');
const { generateTheme } = require('antd-theme-generator');
const options = {
stylesDir: path.join(__dirname, './src/styles'),
antDir: path.join(__dirname, './node_modules/antd'),
varFile: path.join(__dirname, './src/styles/variables.less'),
mainLessFile: path.join(__dirname, './src/styles/index.less'),
themeVariables: [
//需要动态切换的主题变量
'@primary-color',
'@secondary-color',
'@text-color',
'@text-color-secondary',
'@heading-color',
'@layout-body-background'
],
indexFileName: 'index.html',
outputFilePath: path.join(__dirname, './public/color.less') //页面引入的主题变量文件
};
generateTheme(options)
.then(less => {
console.log('Theme generated successfully');
})
.catch(error => {
console.log('Error', error);
});
3、src文件夹下添加styles/index.less+styles/variables.less
@import '~antd/lib/style/themes/default.less';
4、index.html文件中加入全局less配置
index.html 中加入全局 less 变量配置,从而使 less 的 modifyVars 方法可以全局使用,切换主题时覆盖 default.less 中的变量:
<body>
<link
rel="stylesheet/less"
type="text/css"
href="%PUBLIC_URL%/color.less"
rel="external nofollow"
/>
<script>
window.less = {
async: false,
env: 'production'
};
</script>
<script
type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"
></script>
<div id="root" style="height: 100%;"></div>
</body>
5、package.json文件修改命令
"scripts": {
"start": "node color && react-scripts start",
"build": "node color && react-scripts start",
"test": " node color && react-scripts start"
},
6、动态修改颜色
getTheme = color => {
window.less
.modifyVars({
'@primary-color': color,
})
.then(() => {
consolr.log(color);
})
.catch(error => {
console.log(error);
});
};