104 - 《手撕源码 04:unocss》
发布于 2022年4月25日
先介绍下 unocss,官方定义是「The instant on-demand Atomic CSS engine.」。unocss Star 4.2K,周下载 11K,是类 tailwindcss 和 windycss 的方案,可以理解为 utiility-first 的 CSS 框架,提供大量比如 absolute、flex、pt-4、text-center 的 util 类,然后通过组装的方式完成页面样式。同时这些提供的样式是按需编译产出的。
比如,如下 JS 语句。
<div class="absolute i-carbon-logo-github">
hello
</div>
会产出如下 CSS 代码。
/* layer: icons */
[i-carbon-logo-github=""]{…}
/* layer: default */
[absolute=""]{position:absolute;}
unocss 工程化技术栈是 pnpm + eslint + esno + bumpp + tsc + vitest + unbuild。用 esno 编写 scripts,用 version-bump-prompt(bumpp,Star 139)更新 npm 包版本,用 vitest 做测试,而源码构建则基于 unbuild(Star 500+)。.npmrc 中有两个配置,ignore-workspace-root-check=true 允许在根目录通过 pnpm i xxx 安装依赖,shamefully-hoist=true 开启依赖的 hoi