一、使用的插件版本
1、“ant-design-vue” 不限版本
注意:ant-design-vue是基于babel-plugin-import按需引入的,在根目录下建了babel.config.js内容如下
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
],
env: {
development: {
plugins: ['dynamic-import-node'],
},
},
plugins: [
[
'import',
{
libraryName: 'ant-design-vue',
libraryDirectory: 'es',
style: true,
},
],
],
}
2、 "antd-theme-generator": "^1.2.5" 更换主题的核心插件
特别需要注意的是antd-theme-generator如果是用1.2.8版本,则需要在 node-modules/ant-design-vue/lib/style/themes/default.less 文件中添加下面内容,否则会报LessError: error evaluating function darken: color.toHSL is not a function错误,less无法生成
@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;
如果不想改module文件,可以把antd-theme-generator降级到1.2.5版本。
3、 "less": "^2.7.3", "less-loader": "^5.0.0" 因为ant-design-vue是依赖于less进行开发因此安装less和less-loader
二、具体配置
1、在public文件夹下的index.html中加入注释ant design vue切换主题色 下面的代码
<%= webpackConfig.name %>
并建一个空的color.less文件,后面通过node color生成对应的less
2、在根目录下建一个color.js内容如下
const path = require('path')
const { generateTheme } = require('antd-theme-generator')
const options = {
antDir: path.join(__dirname, './node_modules/ant-design-vue'),
stylesDir: path.join(__dirname, './src/assets/styles/theme'),
varFile: path.join(__dirname, './src/assets/styles/theme/variables.less'),
mainLessFile: path.join(__dirname, './src/assets/styles/theme/index.less'),
themeVariables: [
'@primary-color',
'@secondary-color',
'@text-color',
'@text-color-secondary',
'@heading-color',
'@layout-body-background',
'@btn-primary-bg',
'@layout-header-background',
],
indexFileName: 'index.html',
outputFilePath: path.join(__dirname, './public/color.less'),
}
generateTheme(options)
.then(() => {
console.log('Theme generated successfully')
})
.catch((error) => {
console.log('Error', error)
})
3、根据color.js中引入的styles下面的文件我们需要在src/assets/styles下面建一个theme文件夹(可以根据个人习惯建文件夹)里面有【index.less,variables.less,】index.less的内容为空。主要的是variables.less,它的内容如下
@import "~ant-design-vue/lib/style/themes/default.less";
@link-color: #00375B;
@primary-color: rgb(138, 164, 182);
:root {
--PC: @primary-color;
}
.primary-color{
color:@primary-color
}
4、修改package.json中的生成语句中,添加【node color】命令,比如我的是
"serve": "node color && vue-cli-service serve",
"build": "node color && vue-cli-service build",
"build:stage": "node color && vue-cli-service build --mode staging",
只要启动项目就会在public的color.less生成颜色样式
走到这儿动态切换主题色已经可以实现了----(若有问题,欢迎留言)