Ant Design Dynamic Runtime Theme

根据现有需求,需要在运行时更新antd的主题色

项目架构:Create-react-app + antd

由于现有的编译命令,不能使用react-app-rewired命令,只能使用node

 

1. 安装插件

npm install antd-theme-generator antd-theme-webpack-plugin less less-loader react-app-rewire-less react-app-rewired -s

2.  根目录创建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/vars.less'),
  mainLessFile: path.join(__dirname, './src/styles/main.less'),
  themeVariables: [
    '@primary-color'
  ],
  indexFileName: 'index.html',
  outputFilePath: path.join(__dirname, './public/color.less'),
  customColorRegexArray: [/^fade\(.*\)$/]
}

generateTheme(options).then(less => {
  console.log('Theme generated successfully');
})
  .catch(error => {
    console.log('Error', error);
  });

3.  根目录创建config-overrides.js

const path = require('path');
const { injectBabelPlugin } = require('react-app-rewired');
const rewireLess = require('react-app-rewire-less');
const { getLessVars } = require('antd-theme-generator');
/*
# Config
*/
module.exports = function override(config, env) {
  config = injectBabelPlugin(
    ['import', { libraryName: 'antd', style: true }],
    config
  );
  config = rewireLess.withLoaderOptions({
    modifyVars: getLessVars(path.join(__dirname, './src/styles/vars.less')),
    javascriptEnabled: true
  })(config, env);
  return config;
};

4. index.html引入less.min.js

<link rel="stylesheet/less" type="text/css" href="./color.less" />
    <script>
        window.less = {
            async: true,
            env: 'production'
        }
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"></script>

5. main.less

@import "vars.less";
@import "./index.less";

6. var.less

@import "~antd/lib/style/themes/default.less";

7. index.less

// 这里一定是css,不能是less, less的话会把生成的自定义样式覆盖掉!!!!
@import '~antd/dist/antd.css';

 8. 执行脚本

"scripts": {
    "start": "node script/start.js",
    "color": "node color.js",
    "m_start": "run-p color start"
}

 

 

 

上一篇:React遍历antd库的icon出现的一些问题


下一篇:npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree 错误解决