Vite中ElementPlus和TailwindCSS最佳实践(二)
发布于:
前端项目中经常需要同时引用CSS库和UI库,比如
TailwindCSS和ElementPlus一起搭配,设计稿也许完全按照ElementPlus的颜色设计,比如一些重要的或危险的文字色值采用"#F56C6C"(Danger),而TailwindCSS中的text-red-500虽然近似,但终究是无法统一的,接下来我将介绍下, 如何将ElementPlus的Colors扩展到TailwindCSS中。
项目环境
先说明一下实验项目依赖的版本:
- vite:
2.7.2 - vue:
3.2.25 - element-plus:
1.3.0-beta.5 - tailwindcss:
3.0.15
详情可以参考项目:elementplus-tailwindcss-best-practice

知识点
-
CSS变量 这里的TailwindCSS和ElementPlus都有设置一些自定义的CSS变量,前者应用在
*, ::before, ::after(十分巧妙),后者则应用在:root,:root它本身基本等同于html,但在定义全局变量的好处是所有地方都能使用,这里不赘述。 -
TailwindCSS的presets配置 官方介绍的很详细,我这里主要是对
theme进行扩展(extend)默认的colors,详细也可以参考:Customizing the default theme。 -
ElementPlus组件和色彩 一些简单的样式尽可能避免使用组件,比如上面的
el-link,个人感觉并不怎么好看,虽然hover状态的underline可以通过配置移除,但是hover状态的颜色却只能通过重写样式覆盖默认样式来变更,与其这样做,不如直接手写a标 签来实现,hover后的颜色也可以更灵活的调整。 而色彩方面,ELementPlus的规范也并不复杂。更多详细的变量可以去依赖目录中的这里node_modules/element-plus/theme-chalk/src找到。
思考
- 为什么TailwindCSS的变量跟ElementPlus不一样都放在
:root上面; - 为什么TailwindCSS的变量竟然是有空的,例如:
--tw-blur: ;。
延伸阅读:Empty values for variables,看完这个我想大家就基本明了了。
实现部分
根据ElementPlus色彩的文档,写了一个小工具,并不复杂:
const palettes = {
base: ["primary", "success", "warning", "danger", "error", "info"],
hasLight9: ["primary"],
hasLight2: ["success", "warning", "danger", "error", "info"] // danger === error
};
const hasLight9 = function (group) {
const colors = {};
group.forEach(name => {
colors[`el-${name}-light`] = {};
for (let index = 9; index > 0; index--) {
colors[`el-${name}-light`][index * 100] = `var(--el-color-${name}-light-${index})`;
}
});
return colors;
};
const hasLight2 = function (group) {
const colors = {};
group.forEach(name => {
colors[`el-${name}-light`] = `var(--el-color-${name}-light)`;
colors[`el-${name}-lighter`] = `var(--el-color-${name}-lighter)`;
});
return colors;
};
const baseColor = function (group) {
const colors = {};
group.forEach(name => {
colors[`el-${name}`] = `var(--el-color-${name})`;
});
return colors;
};
const getColors = function (palettes) {
const colors = {};
for (const key in palettes) {
const group = palettes[key];
if (key === "base") {
Object.assign(colors, baseColor(group));
} else if (key === "hasLight9") {
Object.assign(colors, hasLight9(group));
} else if (key === "hasLight2") {
Object.assign(colors, hasLight2(group));
}
}
// console.log(colors);
return colors;
};
module.exports = {
theme: {
extend: {
colors: getColors(palettes)
}
}
};
只需要它引入到 tailwind.config.js 中即可。如果在VSCode中有安装插件Tailwind CSS IntelliSense,那会更方便,不过目前有一点麻烦的事情就是,敲 class= 时出现了 "" 后就没有提示,要么进入 "" 输入 空格 触发,要么删除 "" ,再敲一个 " 来触发提示。现在在 class 内输入 el- 就能出现ElementPlus的色彩了~
经过一番优化,终于能使用色彩相同的样式了。
whidy
一名爱折腾的前端开发工程师,喜欢打篮球和分享 ฅʕ•̫͡•ʔฅ