🍃你是否在为一个组件的样式就占了整个组件的 30% 甚至更多的代码而烦恼吗?今天的目的就只有一个,从编写样式上,怎么让后台管理系统的组件变得优雅。
官方文档: unocss.nodejs.cn
使用步骤 UnoCSS
1. 安装: pnpm add -D unocss
2. 配置: 在 vite.config.ts
文件中配置如下
typescript
import UnoCSS from 'unocss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
UnoCSS(),
],
})
3. 创建 uno.config.ts
文件
typescript
import { defineConfig } from 'unocss'
export default defineConfig({
// ...UnoCSS options
})
4. 将 virtual:uno.css
添加到你的主入口中
typescript
// main.ts
import 'virtual:uno.css'
看到这里肯定有同学会问,CSS 预处理器 Sass
、SCSS
、Less
、Stylus
已经让我们极大方便编写 CSS
样式了,怎么还要介绍这个工具?我们看下面的简单对比就能知道它的魅力了,实际开发中我们一般选一个 CSS 预处理器加上 UnoCSS
工具更高效。
编写对比
传统编写方式
typescript
<template>
<table class="data-table">
<thead>
<tr>
<th>标题</th>
<!-- 更多表头 -->
</tr>
</thead>
</table>
</template>
<style scoped>
.data-table {
border: 1px solid #e5e7eb;
border-collapse: collapse;
width: 100%;
}
.data-table th {
background-color: #f3f4f6;
padding: 12px 16px;
text-align: left;
}
/* 更多样式... */
</style>
UnoCSS
编写方式
typescript
<template>
<table
border="1"
class="border-gray-200 w-full collapse"
>
<thead>
<tr>
<th class="bg-gray-100 p-3 text-left">标题</th>
<!-- 更多表头 -->
</tr>
</thead>
</table>
</template>
实现相同样式的目的,代码可读性上却有着不同的表现,UnoCSS
让编写样式上大大减少了维护成本。
我觉得唯一的缺点是,在没接触 UnoCSS
之前,需要花点时间熟悉它的语法🤣。