前面项目下载配置了一些插件,这次还要配置,这次配置的项目的自定义换肤
前言换肤功是参照 github上找的一个不错的项目:
[链接]: ( https://github.com/hsl947/react-antd-multi-tabs-admin)
1.首先配置pubilc文件中index.html文件。
https://github.com/hsl947/react-antd-multi-tabs-admin
上面链接项目中的pubilc文件中的less.min.js , color.less文件赋值到自己项目中的pubilc中。
然后pubilc中的index.html中的body中添加如下代码:
<body>
<!-- 主题 -->
<link type="text/css" rel="stylesheet/less" href="/color.less">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script>
// 切换为当前主题
const themeStyle = localStorage.getItem('themeStyle')
if(themeStyle) {
const styles = document.createElement('style')
styles.id = 'less:color'
styles.innerText = themeStyle
document.body.appendChild(styles)
console.log("创建less:id");
}
</script>
</body>
2.在config-overrides.js中增加addLessLoader配置
config-overrides.js之前的文章有
const {
override,
addDecoratorsLegacy,
disableEsLint,
addWebpackAlias,
fixBabelImports,
addLessLoader
} = require("customize-cra")
const path = require("path");
const darkThemeVars = require('antd/dist/dark-theme');
module.exports = override(
// 添加装饰器
addDecoratorsLegacy(),
disableEsLint(),
// 设置路径别名
addWebpackAlias({
'@': path.resolve(__dirname, 'src'),
}),
// 按需加载
fixBabelImports("import", {
libraryName: "antd",
libraryDirectory: "es",
style: true
}),
// 使用less-loader对源码重的less的变量进行重新制定,设置antd自定义主题
addLessLoader({
javascriptEnabled: true,
modifyVars: {
'hack': `true;@import "${require.resolve('antd/lib/style/color/colorPalette.less')}";`,
...darkThemeVars,
'@primary-color': '#6e41ff',
},
})
);
3. app.tsx(没用ts就是app.js)
将app.css改成app.less,并添加:
@import '~antd/dist/antd.less';
app.tsx中 import './App.css'改成:
import './App.less';
之后就是在app.tsx文件中测试下效果:
import React,{FC,useEffect} from 'react';
import {Button} from 'antd' //引入按钮组件
import './App.less';
const App:FC=()=> {
useEffect(() => {
const script = document.createElement('script')
script.id = 'themeJs'
script.src = '/less.min.js'
document.body.appendChild(script)
setTimeout(() => {
const themeStyle = document.getElementById('less:color')
if (themeStyle) localStorage.setItem('themeStyle', themeStyle.innerText)
}, 500)
}, [])
useEffect(() => {
setTimeout(() => {
console.log("替换");
const themeJs = document.getElementById('themeJs')
const themeStyle = document.getElementById('less:color')
if (themeJs) themeJs.remove()
if (themeStyle) themeStyle.remove()
localStorage.removeItem('themeStyle')
}, 4000)
}, [])
return (
<div className="App">
app index
<br/>
<Button type="primary">Primary Button</Button>
<button>点我</button>
<Button type="primary">
Search
</Button>
</div>
);
}
export default App;
image-20210121113555563.png
4s后
image-20210121113510937.png实现了简单的亮色和暗色的换肤功能。
网友评论