需要的用的库
"antd-theme-generator": "^1.2.6", // 我在项目中用其他版本出现 color.toHash
"less": "^2.7.3"
实现步骤
在项目中新建存放主题相关的文件夹
styles
, 在styles
中新建index.less
(可以为空),var.less
(主题色的配置)
@import "~ant-design-vue/lib/style/themes/default.less";
// ant design vue 主题配置
@link-color: #1890ff;
@primary-color: #1890ff;
@layout-header-background: #feffff;
@menu-item-active-bg: #feffff;
@menu-highlight-color: #feffff;
@layout-body-background: #feffff;
:root {
--PC: @primary-color; //color.less中加入css原生变量:--PC
}
.primary-color{
color:@primary-color
}
在项目的跟目录新建
color.js
const path = require('path');
const { generateTheme } = require('antd-theme-generator');
// ant-design-vue/dist/antd.less
const options = {
antDir: path.join(__dirname, './node_modules/ant-design-vue'), //对应具体位置
stylesDir: path.join(__dirname, './src/styles'), //对应具体位置
varFile: path.join(__dirname, './src/styles/var.less'), //对应具体位置
mainLessFile: path.join(__dirname, './src/styles/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);
});
在
package.json
中替换scripts
中的命令
"scripts": {
"serve": "node color && vue-cli-service serve --mode dev",
"build": "node color && vue-cli-service build --mode prod"
},
tips 注意点
// 文件的路径为 /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;
执行
yarn serve
在public
中出现color.less
即可
修改 index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<link rel="icon" href="<%= BASE_URL %>favicon.ico" />
<title><%= htmlWebpackPlugin.options.title %></title>
<!-- 引入color.less -->
<link rel="stylesheet/less" type="text/css" href="/color.less" />
</head>
<body>
<noscript>
<strong
>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work
properly without JavaScript enabled. Please enable it to
continue.</strong
>
</noscript>
<div id="app"></div>
<script>
window.less = {
async: false,
env: "production",
};
</script>
<!-- 引入less.js -->
<script type="text/javascript" src="./less.min.js"></script>
<!-- built files will be auto injected -->
</body>
</html>
在项目中进行调用
window.less.modifyVars({
"@primary-color": color,
"@link-color": color,
"@btn-primary-bg": color,
})
.then(() => {
console.log("成功");
})
.catch((error) => {
alert("失败");
console.log(error);
});