背景
公司需求:在项目运行时支持更换主题。项目vue为3.0版本,antd版本为2.0.0,网络上关于
antd-theme-generator教程有些坑点没有写的很详细,这里记录总结一下
原理
使用 less 的 modifyVars 来更改主题。
插件
antd-theme-generator(只是针对于颜色的定制,对于其他属性例如字体大小,边框,边距等样式不提供定制) 或者 antd-theme-webpack-plugin(基于antd-theme-generator开发的一个插件),本文主要讲 antd-theme-generator 的使用
antd-theme-generator 插件
步骤一:安装
yarn add antd-theme-generator@1.2.6 –save
步骤二:配置 color.js
安装完成在根目录下创建color.js文件, 文件配置如下:
const { generateTheme } = require('antd-theme-generator');
const path = require('path');
const options = {
stylesDir: path.join(__dirname, './src/styles/theme'), //主题文件所在文件夹
antDir: path.join(__dirname, './node_modules/ant-design-vue'), //antd包位置
varFile: path.join(__dirname, './src/styles/theme/variables.less'), // 自定义默认的主题色
mainLessFile: path.join(__dirname, './src/styles/theme/index.less'), // 项目中其他自定义的样式(如果不需要动态修改其他样式,该文件可以为空)
themeVariables: [ '@primary-color'], //要改变的主题变量
indexFileName: 'index.html', // index.html所在位置
outputFilePath: path.join(__dirname, './public/theme.less'), // 是否只生成一次
}
generateTheme(options).then(less => {
console.log('Theme generated successfully');
})
.catch(error => {
console.log('Error', error);
})
步骤三:运行 color.js
完成配置之后(以下方式二选一即可)
(1)可以在vue.config.js获取
require('./color')
(2)配置package.json的scripts
serve(开发环境),build(生产环境)属性中中添加 node color &&
添加完配置,/src/styles/ 创建一个 theme 文件夹,文件夹下创建文件 variables.less 和 index.less文件
index.less文件内容可以为空,variables.less 文件内容:
// 这段样式引入必须添加
@import "~ant-design-vue/lib/style/themes/default.less";
@primary-color: #992777;
文件创建完毕,执行启动开发环境命令 yarn run serve
,打包成功在public文件夹会有一个,theme.less 文件,如图:
步骤四:index.html 写入
<head>
...
<script>
window.less = {
'async': false,
'env': 'production'//production development
};
</script>
...
</head>
<body>
...
<link rel="stylesheet/less" type="text/css" href="./theme.less" />
<div id="app"></div>
<script src="https://cdn.bootcss.com/less.js/2.7.3/less.min.js"></script>
...
</body>
使用
window.less.modifyVars({
'@primary-color': 'red'
})
.then(() => {
console.log('成功');
})
.catch((error: any) => {
alert('失败');
console.log(error);
});
注意事项
1. antd-theme-generator版本问题
推荐使用:yarn add antd-theme-generator@1.2.6 --save
如果使用的是antd-theme-generator@1.2.8版本,会出现报错:
error [LessError: error evaluating function `darken`: color.toHSL is not a function]
解决方案:
找到 /node_modules/ant-design-vue/lib/style/themes/default.less 这个文件
找到 // Table 在其下面添加以下代码块:
@table-header-sort-active-bg: darken(@table-header-bg, 3%);
@table-header-filter-active-bg: darken(@table-header-sort-active-bg, 5%);
@table-selection-column-width: 60px;
如图:
antd-theme-webpack-plugin@1.3.9 版本会出现相同的问题,可以用这种方法解决
2. 样式覆盖,样式不出现的问题
-
注意theme.less的 link标签放的位置,要放在body的第一行里,因为到时候style是会生成在该ling标签下面的,如果你把link放在head里,到时候生成的主题样式会被覆盖掉。
-
我们需要在theme.less 的link 的下方引入cdn.bootcss.com/less.js/2.7… (less版本不可以超过3.0)文件,因为我们需要使用到window.less这个对象里的方法,但是我们不能引入less3.0以上的,不然浏览器控制台会报错,样式也不会出现。
链接
antd-theme-generator:github.com/mzohaibqc/a…
antd-theme-webpack-plugin: github.com/mzohaibqc/a…