原子化 CSS 是一种 CSS 的架构方式,它倾向于小巧且用途单一的 class,并且会以视觉效果进行命名。
看的一脸懵逼是不是,刚开始俺也一样。
第一次见还是在大佬代码里看到的,一堆text-14px c-flex
类似的类。以为是自己定义的属性,全局搜了下发现是使用了UnoCSS
。
安装
1
| npm i -D unocss @unocss/webpack @unocss/cli
|
@unocss/webpack用于webpack项目可以使用unocss。
@unocss/cli则是unocss的脚手架,可以实现监听文件实时增减对应的class。
使用
以下示例代码均基于vue3.x + webpack
首先在package.json新增脚本
1 2 3 4
| "scripts": { "unocss": "unocss \"src*.vue\" -w -m false -o src/common/css/unocss.css" },
|
在main.js中引入
1 2
| import '@/common/css/unocss.css';
|
在项目根目录下创建文件unocss.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import { defineConfig, presetUno, transformerVariantGroup } from "unocss"; export default defineConfig({ preprocess(matcher) { return matcher.startsWith("c-") ? matcher.slice(2) : undefined; }, presets: [ presetUno(), ], transformers: [transformerVariantGroup()], shortcuts: [ { btn: "box-border block w-220px p:w-280px mx-auto bg-brand/100 leading-20px py-12px text-center text-white/100 overflow-hidden rounded-36px transition-colors", }, ], rules: [["bg-full", { "background-size": "100% 100%" }]], theme: { breakpoints: { xs: "0px", sm: "320px", md: "640px", }, colors: { dark: "#000000", brand: "#2D40E9", }, }, });
|