企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
利用[webpack-theme-color-replacer](https://link.segmentfault.com/?url=https%3A%2F%2Fgithub.com%2Fhzsrc%2Fwebpack-theme-color-replacer)插件,为[ant-design](https://link.segmentfault.com/?url=https%3A%2F%2Fgithub.com%2Fant-design%2Fant-design)实现在运行时动态切换主题色的功能,无需在页面进行less的编译,提升切换速度 利用[webpack-theme-color-replacer](https://github.com/hzsrc/webpack-theme-color-replacer)插件,在webpack构建时提取css中含有主题色的样式规则,生成一个css/theme-colors.css文件。然后在网页运行时,下载这个css文件,动态替换其中的颜色为自定义主题色。 ***** **安装** `npm i -D webpack-theme-color-replacer` **引入插件,修改配置** ``` constThemeColorReplacer\=require("webpack-theme-color-replacer"); const { getThemeColors,modifyVars } \=require("./src/utils/themeUtil"); module.exports\={ configureWebpack:config\=>{ config.plugins.push( newThemeColorReplacer({ fileName:"css/theme-colors-\[contenthash:8\].css", matchColors:getThemeColors(), injectCss:true }) ); }, css:{ loaderOptions:{ less:{ lessOptions:{ modifyVars:modifyVars(), javascriptEnabled:true } } } } } ``` utils目录下新增colors.js和themeUtil.js两个文件 color.js ``` // 蚂蚁设计的调色板计算器 const { generate } \=require("@ant-design/colors"); // 获取 ant design 色系 functiongetAntdColors(color){ return generate(color); } // 获取切换色系 functiongetThemeToggleColors(color){ // 主色系 constmainColors\=getAntdColors(color); constprimary\=mainColors\[10\]; return {primary,mainColors}; } module.exports\={ getAntdColors, getThemeToggleColors }; ``` themeUtil.js ``` constclient\=require("webpack-theme-color-replacer/client"); const { getThemeToggleColors,getAntdColors } \=require("./colors.js"); functiongetThemeColors(color){ const\_color\=color; constreplaceColors\=getThemeToggleColors(\_color); constthemeColors\=\[...replaceColors.mainColors\]; return themeColors; } // 调用插件内的方法 functionchangeThemeColor(newColor){ letpromise\=client.changer.changeColor({newColors:getThemeColors(newColor)}); return promise; } functionmodifyVars(color){ let _color = color; const palettes=getAntdColors(\_color); const primary=palettes\[5\]; return{ "primary-color":primary, "primary-1":palettes\[0\], "primary-2":palettes\[1\], "primary-3":palettes\[2\], "primary-4":palettes\[3\], "primary-5":palettes\[4\], "primary-6":palettes\[5\], "primary-7":palettes\[6\], "primary-8":palettes\[7\], "primary-9":palettes\[8\], "primary-10":palettes\[9\], "info-color":primary, "alert-info-bg-color":palettes\[0\], "alert-info-border-color":palettes\[2\], "processing-color":primary }; } module.exports\={ getThemeColors, changeThemeColor, modifyVars }; ```