当前位置: 首页 > Web前端 > CSS

webpack插件-css主题颜色提取-主题切换

时间:2023-03-30 15:09:06 CSS

css-color-extract-pluginInstallnpminstallcss-color-extract-pluginyarnaddcss-color-extract-plugin这个插件主要用来提取主题颜色提取出来的css数据会挂载到window上,然后通过color插入到,可以达到动态修改主题的目的Usage//webpack.config.jsconstCssColorExtractPlugin=require('css-color-extract-plugin').default;constPRIMARY_COLOR='#1890ff';module.exports={...模块:{规则:[{测试:/\.css$/,排除:'/\.module\.css$/',使用:[“style-loader”,“css-loader”,{loader:CssColorExtractPlugin。加载器,选项:{颜色:[PRIMARY_COLOR]}},]},{测试:/\.module\.css$/,使用:[“style-loader”,{加载器:“css-loader”,选项:{模块:true,localIdentName:'[path][name]__[local]',}},{loader:CssColorExtractPlugin.loader,options:{colors:[PRIMARY_COLOR],modules:true,localIdentName:'[path][name]__[local]}]',}},]}]}...plugins:[...newCssColorExtractPlugin({fileName:'theme'}),]};编写后会在html中插入theme.js,其内容类如下window.CSS_EXTRACT_COLOR_PLUGIN=[{"source":".src-App-module__example{background:#1890ff;}","fileName":"App.module.scss","matchColors":["#1890ff"]},{“来源”:“.src-controller-blog-components-Header-Header-module__theme{color:#067785;}.src-controller-blog-components-Header-Header-module__pc_header{background:#1890ff;}.src-controller-blog-components-Header-Header-module__mb_header{背景:#1890ff;}.src-controller-blog-components-Header-Header-module__mb_header.src-controller-blog-components-Header-Header-module__mb_nav{background:#1890ff;}","fileName":"Header.module.scss","matchColors":["#1890ff"]}];继续只使用简单的正确规则即可更换主题色importReact,{Component}from'react';importstylesfrom'./App.module.scss';import{SketchPicker}from'react-color';functionreplaceColor(source,color,replaceColor){returnsource.replace(newRegExp(`(:.*?\\s*)(${color})(\\b.*?)(?=})`,'mig'),(group)=>{returngroup.replace(newRegExp(`${color}`,'mig'),replaceColor);});}constPRIMARY_COLOR='#1890ff';classAppextendsComponent{asyncsetColor(color){conststyleData=window.CSS_EXTRACT_COLOR_PLUGIN||[];constcssText=styleData.map((item)=>item.source).join('');conststyleText=replaceColor(cssText,PRIMARY_COLOR,color);conststyle=document.createElement('style');style.innerHTML=styleText;document.body.appendChild(样式);}render(){return(this.setColor(colorResult.hex)}/>

);}}exportdefaultApp;loaderOptions{colors:string[];//匹配颜色数组,如果有颜色层错误覆盖,需要选择被覆盖的颜色,可以在Differentfilesextractdifferentcolorsonly?:boolean=true;//只提取选中的颜色规则,否则整个文件将被提取modules?:boolean=false;localIdentName?:string='';}插件选项{文件名?:细绳;//提取颜色的文件名,如果不提供,会直接嵌入到脚本标签中variableName?:string='CSS_EXTRACT_COLOR_PLUGIN';//挂载到窗口的变量名,默认CSS_EXTRACT_COLOR_PLUGIN}example一个更复杂的例子-RyanCMS内容管理系统