本章概述
本章将全面介绍 UnoCSS 的生态系统,包括官方工具、社区插件、IDE 支持、学习资源等,帮助你更好地利用社区力量提升开发效率。
官方生态系统
核心包
1. 主要包结构
# 核心包
npm install unocss
# 分包安装(按需)
npm install @unocss/core # 核心引擎
npm install @unocss/cli # 命令行工具
npm install @unocss/preset-uno # Uno 预设
npm install @unocss/preset-wind # Wind 预设
npm install @unocss/preset-mini # Mini 预设
npm install @unocss/preset-icons # 图标预设
npm install @unocss/preset-attributify # 属性化预设
npm install @unocss/preset-typography # 排版预设
npm install @unocss/preset-web-fonts # Web字体预设
# 构建工具集成
npm install @unocss/vite # Vite 插件
npm install @unocss/webpack # Webpack 插件
npm install @unocss/postcss # PostCSS 插件
npm install @unocss/nuxt # Nuxt 模块
npm install @unocss/astro # Astro 集成
# 转换器
npm install @unocss/transformer-directives # 指令转换器
npm install @unocss/transformer-variant-group # 变体组转换器
npm install @unocss/transformer-compile-class # 编译类转换器
npm install @unocss/transformer-attributify-jsx # JSX属性化转换器
2. 包功能详解
// 核心引擎使用
import { createGenerator } from '@unocss/core'
import presetUno from '@unocss/preset-uno'
const generator = createGenerator({
presets: [presetUno()],
})
// 生成CSS
const { css } = await generator.generate('flex items-center justify-center')
console.log(css)
// CLI工具使用
// package.json scripts
{
"scripts": {
"build:css": "unocss 'src/**/*.{vue,js,ts,jsx,tsx}' -o dist/uno.css",
"watch:css": "unocss 'src/**/*.{vue,js,ts,jsx,tsx}' -o dist/uno.css --watch",
"dev:inspector": "unocss --dev"
}
}
官方工具
1. UnoCSS Inspector
// 启用检查器
export default defineConfig({
// 开发模式启用
inspector: process.env.NODE_ENV === 'development',
// 自定义检查器配置
inspector: {
// 检查器端口
port: 5173,
// 检查器主机
host: 'localhost',
// 是否自动打开
open: true,
// 检查器路径
path: '/__unocss',
},
})
// 访问检查器
// http://localhost:5173/__unocss
检查器功能: - 实时预览:查看生成的CSS - 类名搜索:快速查找类名对应的CSS - 规则调试:查看规则匹配过程 - 性能分析:分析生成性能 - 配置查看:查看当前配置
2. VS Code 扩展
// .vscode/extensions.json
{
"recommendations": [
"antfu.unocss", // UnoCSS 官方扩展
"bradlc.vscode-tailwindcss", // Tailwind CSS 智能感知
"formulahendry.auto-rename-tag", // 自动重命名标签
"esbenp.prettier-vscode" // 代码格式化
]
}
// .vscode/settings.json
{
// UnoCSS 配置
"unocss.root": "./",
"unocss.configFile": "uno.config.js",
// 启用智能感知
"editor.quickSuggestions": {
"strings": true
},
// 文件关联
"files.associations": {
"*.css": "css",
"*.uno.css": "css"
},
// 格式化配置
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true
}
}
扩展功能: - 语法高亮:UnoCSS 类名高亮 - 智能补全:类名自动补全 - 悬停提示:显示生成的CSS - 错误检查:无效类名提示 - 快速修复:常见问题修复建议
3. 命令行工具
# 基础用法
unocss "src/**/*.{vue,js,ts,jsx,tsx}" -o dist/uno.css
# 监听模式
unocss "src/**/*.{vue,js,ts,jsx,tsx}" -o dist/uno.css --watch
# 指定配置文件
unocss "src/**/*.{vue,js,ts,jsx,tsx}" -o dist/uno.css -c uno.config.js
# 压缩输出
unocss "src/**/*.{vue,js,ts,jsx,tsx}" -o dist/uno.css --minify
# 生成预检样式
unocss --preflights -o dist/preflights.css
# 启动开发服务器
unocss --dev
# 分析模式
unocss "src/**/*.{vue,js,ts,jsx,tsx}" --analyze
# 帮助信息
unocss --help
4. 在线工具
// UnoCSS Playground 配置
const playgroundConfig = {
// 在线地址
url: 'https://uno.antfu.me/',
// 功能特性
features: [
'实时编辑和预览',
'配置文件编辑',
'多种预设选择',
'代码分享功能',
'导出功能',
],
// 使用场景
useCases: [
'快速原型设计',
'学习和实验',
'问题复现',
'配置测试',
'团队协作',
],
}
// 分享配置示例
const shareableConfig = {
presets: [
presetUno(),
presetAttributify(),
],
rules: [
['custom-rule', { color: 'red' }],
],
shortcuts: {
'btn': 'px-4 py-2 rounded bg-blue-500 text-white',
},
}
社区生态
社区预设
1. 流行的社区预设
// 动画预设
import { presetAnimations } from 'unocss-preset-animations'
export default defineConfig({
presets: [
presetUno(),
presetAnimations({
// 动画配置
duration: {
'fast': '150ms',
'normal': '300ms',
'slow': '500ms',
},
// 缓动函数
easing: {
'ease-in-out-back': 'cubic-bezier(0.68, -0.55, 0.265, 1.55)',
'ease-in-out-circ': 'cubic-bezier(0.785, 0.135, 0.15, 0.86)',
},
// 预定义动画
animations: {
'fade-in': 'fadeIn 0.3s ease-in-out',
'slide-up': 'slideUp 0.3s ease-out',
'bounce-in': 'bounceIn 0.6s ease-out',
},
}),
],
})
// 表单预设
import { presetForms } from '@unocss/preset-forms'
export default defineConfig({
presets: [
presetUno(),
presetForms({
// 表单样式策略
strategy: 'base', // 'base' | 'class'
// 自定义表单样式
customizations: {
input: {
'border-radius': '0.375rem',
'border-width': '1px',
'padding': '0.5rem 0.75rem',
},
button: {
'border-radius': '0.375rem',
'padding': '0.5rem 1rem',
'font-weight': '500',
},
},
}),
],
})
// 滚动条预设
import { presetScrollbar } from 'unocss-preset-scrollbar'
export default defineConfig({
presets: [
presetUno(),
presetScrollbar({
// 滚动条配置
scrollbarWidth: {
'thin': '8px',
'normal': '12px',
'thick': '16px',
},
// 滚动条颜色
scrollbarColor: {
'primary': '#3b82f6',
'secondary': '#6b7280',
},
}),
],
})
2. 主题预设
// Material Design 预设
import { presetMaterial } from 'unocss-preset-material'
export default defineConfig({
presets: [
presetUno(),
presetMaterial({
// Material Design 配置
theme: 'light', // 'light' | 'dark' | 'auto'
// 颜色系统
colors: {
primary: '#1976d2',
secondary: '#dc004e',
surface: '#ffffff',
background: '#fafafa',
},
// 组件样式
components: {
button: true,
card: true,
input: true,
dialog: true,
},
// 阴影系统
elevation: {
1: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)',
2: '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)',
3: '0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23)',
},
}),
],
})
// Ant Design 预设
import { presetAntd } from 'unocss-preset-antd'
export default defineConfig({
presets: [
presetUno(),
presetAntd({
// Ant Design 配置
theme: {
primaryColor: '#1890ff',
successColor: '#52c41a',
warningColor: '#faad14',
errorColor: '#f5222d',
},
// 组件前缀
prefix: 'ant-',
// 启用的组件
components: [
'button',
'input',
'card',
'table',
'form',
],
}),
],
})
社区插件
1. 实用插件
// 渐变插件
import { gradientPlugin } from 'unocss-plugin-gradient'
export default defineConfig({
plugins: [
gradientPlugin({
// 渐变方向
directions: {
'to-r': 'to right',
'to-br': 'to bottom right',
'to-t': 'to top',
},
// 预定义渐变
gradients: {
'sunset': 'linear-gradient(45deg, #ff6b6b, #feca57)',
'ocean': 'linear-gradient(135deg, #667eea, #764ba2)',
'forest': 'linear-gradient(90deg, #56ab2f, #a8e6cf)',
},
}),
],
})
// 使用方式
// <div class="bg-gradient-sunset">渐变背景</div>
// <div class="bg-gradient-to-r from-blue-500 to-purple-600">自定义渐变</div>
// 阴影插件
import { shadowPlugin } from 'unocss-plugin-shadow'
export default defineConfig({
plugins: [
shadowPlugin({
// 阴影预设
shadows: {
'soft': '0 2px 8px rgba(0, 0, 0, 0.1)',
'medium': '0 4px 16px rgba(0, 0, 0, 0.15)',
'hard': '0 8px 32px rgba(0, 0, 0, 0.2)',
'colored': '0 4px 16px rgba(59, 130, 246, 0.3)',
},
// 内阴影
insetShadows: {
'soft': 'inset 0 2px 4px rgba(0, 0, 0, 0.1)',
'medium': 'inset 0 4px 8px rgba(0, 0, 0, 0.15)',
},
}),
],
})
// 使用方式
// <div class="shadow-soft">软阴影</div>
// <div class="shadow-inset-medium">内阴影</div>
2. 框架特定插件
// React 插件
import { reactPlugin } from 'unocss-plugin-react'
export default defineConfig({
plugins: [
reactPlugin({
// React 特定功能
jsx: true,
// 组件样式
components: {
// 自动生成 React 组件样式
'Button': {
base: 'px-4 py-2 rounded font-medium transition-colors',
variants: {
primary: 'bg-blue-500 text-white hover:bg-blue-600',
secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300',
},
},
},
}),
],
})
// Vue 插件
import { vuePlugin } from 'unocss-plugin-vue'
export default defineConfig({
plugins: [
vuePlugin({
// Vue 特定功能
sfc: true,
// 指令支持
directives: {
'v-loading': 'animate-spin',
'v-show': 'transition-opacity',
},
// 组件库集成
componentLibrary: 'element-plus', // 'element-plus' | 'ant-design-vue' | 'vuetify'
}),
],
})
IDE 支持
1. VS Code 扩展生态
// 推荐扩展配置
{
"recommendations": [
// UnoCSS 官方扩展
"antfu.unocss",
// 相关扩展
"bradlc.vscode-tailwindcss", // Tailwind CSS 支持
"formulahendry.auto-rename-tag", // 标签重命名
"christian-kohler.path-intellisense", // 路径智能感知
"ms-vscode.vscode-typescript-next", // TypeScript 支持
// 代码质量
"esbenp.prettier-vscode", // 代码格式化
"dbaeumer.vscode-eslint", // ESLint
"stylelint.vscode-stylelint", // Stylelint
// 开发工具
"ms-vscode.live-server", // 实时服务器
"ritwickdey.liveserver", // Live Server
"ms-vscode.vscode-json", // JSON 支持
]
}
// 工作区配置
{
// UnoCSS 特定配置
"unocss.root": "./",
"unocss.configFile": "uno.config.ts",
"unocss.colorPreview": true,
"unocss.underline": true,
// 编辑器配置
"editor.quickSuggestions": {
"other": true,
"comments": false,
"strings": true
},
// 文件关联
"files.associations": {
"*.uno.css": "css",
"uno.config.*": "javascript"
},
// 智能感知配置
"typescript.preferences.includePackageJsonAutoImports": "on",
"typescript.suggest.autoImports": true,
// 格式化配置
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.formatOnType": false,
// CSS 相关配置
"css.validate": false,
"less.validate": false,
"scss.validate": false,
// 代码片段
"editor.snippetSuggestions": "top",
"editor.tabCompletion": "on"
}
2. 其他 IDE 支持
// WebStorm 配置
const webstormConfig = {
// 文件模板
fileTemplates: {
'UnoCSS Config': {
extension: 'js',
content: `
import { defineConfig, presetUno } from 'unocss'
export default defineConfig({
presets: [
presetUno(),
],
rules: [
// 自定义规则
],
shortcuts: {
// 快捷方式
},
})
`,
},
},
// 代码检查
inspections: {
'UnoCSS Class Names': {
enabled: true,
severity: 'warning',
},
},
// 实时模板
liveTemplates: {
'uno-config': {
abbreviation: 'unoconfig',
template: 'defineConfig({\n presets: [presetUno()],\n $END$\n})',
},
},
}
// Vim/Neovim 配置
const vimConfig = `
" UnoCSS 配置
" 安装 coc-unocss 插件
:CocInstall coc-unocss
" 或使用 nvim-lsp
lua << EOF
require'lspconfig'.unocss.setup{
filetypes = { 'html', 'vue', 'jsx', 'tsx', 'svelte' },
settings = {
unocss = {
configFile = 'uno.config.js'
}
}
}
EOF
" 语法高亮
autocmd BufRead,BufNewFile *.uno.css set filetype=css
" 快捷键映射
nnoremap <leader>uc :!unocss "src/**/*.{vue,js,ts,jsx,tsx}" -o dist/uno.css<CR>
`
学习资源
官方文档
// 文档结构
const officialDocs = {
// 主要文档
main: {
url: 'https://unocss.dev/',
sections: [
'Getting Started',
'Presets',
'Rules',
'Variants',
'Transformers',
'Extractors',
'Config',
],
},
// API 文档
api: {
url: 'https://unocss.dev/api/',
coverage: [
'Core API',
'Preset API',
'Plugin API',
'Transformer API',
],
},
// 示例
examples: {
url: 'https://github.com/unocss/unocss/tree/main/examples',
projects: [
'Vite + Vue',
'Vite + React',
'Nuxt',
'SvelteKit',
'Astro',
'Next.js',
],
},
}
社区教程
1. 博客文章
// 推荐博客文章
const recommendedArticles = [
{
title: 'UnoCSS: The Instant On-Demand Atomic CSS Engine',
author: 'Anthony Fu',
url: 'https://antfu.me/posts/unocss',
topics: ['Introduction', 'Philosophy', 'Performance'],
},
{
title: 'Migrating from Tailwind CSS to UnoCSS',
author: 'Community',
topics: ['Migration', 'Comparison', 'Best Practices'],
},
{
title: 'Building a Design System with UnoCSS',
author: 'Community',
topics: ['Design System', 'Components', 'Theming'],
},
{
title: 'UnoCSS Performance Optimization Guide',
author: 'Community',
topics: ['Performance', 'Bundle Size', 'Build Time'],
},
]
// 学习路径
const learningPath = {
beginner: [
'了解原子化 CSS 概念',
'安装和基础配置',
'学习基础预设',
'掌握常用工具类',
'实践简单项目',
],
intermediate: [
'自定义规则和变体',
'创建组件库',
'性能优化技巧',
'团队协作规范',
'复杂项目实践',
],
advanced: [
'开发自定义预设',
'创建插件生态',
'贡献开源项目',
'技术分享和教学',
'生态系统建设',
],
}
2. 视频教程
// 视频教程资源
const videoTutorials = {
// YouTube 频道
youtube: [
{
channel: 'Anthony Fu',
videos: [
'UnoCSS Introduction',
'Building with UnoCSS',
'Advanced UnoCSS Techniques',
],
},
{
channel: 'Vue Mastery',
videos: [
'UnoCSS with Vue 3',
'Styling Vue Components',
],
},
],
// 在线课程
courses: [
{
platform: 'Udemy',
title: 'Complete UnoCSS Course',
duration: '8 hours',
level: 'Beginner to Advanced',
},
{
platform: 'Pluralsight',
title: 'Modern CSS with UnoCSS',
duration: '4 hours',
level: 'Intermediate',
},
],
// 直播和研讨会
webinars: [
{
title: 'UnoCSS Best Practices',
host: 'Vue.js Community',
frequency: 'Monthly',
},
{
title: 'Building Design Systems',
host: 'Frontend Masters',
frequency: 'Quarterly',
},
],
}
社区支持
1. 官方社区
// 社区平台
const communityPlatforms = {
// GitHub
github: {
repository: 'https://github.com/unocss/unocss',
features: [
'Issue 追踪',
'Pull Request',
'Discussions',
'Wiki',
'Releases',
],
// 贡献指南
contributing: {
codeOfConduct: 'https://github.com/unocss/unocss/blob/main/CODE_OF_CONDUCT.md',
contributingGuide: 'https://github.com/unocss/unocss/blob/main/CONTRIBUTING.md',
issueTemplate: 'https://github.com/unocss/unocss/tree/main/.github/ISSUE_TEMPLATE',
},
},
// Discord
discord: {
server: 'Vue Land',
channels: [
'#unocss-help',
'#unocss-showcase',
'#unocss-development',
],
},
// Twitter
twitter: {
hashtags: ['#UnoCSS', '#AtomicCSS', '#VueJS'],
accounts: ['@antfu7', '@unocss'],
},
}
2. 问答平台
// 问答资源
const qaResources = {
// Stack Overflow
stackoverflow: {
tag: 'unocss',
commonQuestions: [
'How to configure UnoCSS with Vite?',
'UnoCSS vs Tailwind CSS comparison',
'Custom rules in UnoCSS',
'Performance optimization tips',
],
},
// Reddit
reddit: {
subreddits: [
'r/vuejs',
'r/Frontend',
'r/webdev',
'r/css',
],
},
// 中文社区
chinese: {
platforms: [
'掘金 (Juejin)',
'思否 (SegmentFault)',
'知乎 (Zhihu)',
'CSDN',
],
},
}
贡献指南
如何贡献
1. 代码贡献
# 1. Fork 项目
git clone https://github.com/your-username/unocss.git
cd unocss
# 2. 安装依赖
pnpm install
# 3. 创建分支
git checkout -b feature/your-feature-name
# 4. 开发和测试
pnpm dev
pnpm test
# 5. 提交代码
git add .
git commit -m "feat: add your feature"
git push origin feature/your-feature-name
# 6. 创建 Pull Request
2. 开发环境设置
// 开发脚本
const devScripts = {
// 构建
build: 'pnpm build',
// 测试
test: 'pnpm test',
'test:watch': 'pnpm test --watch',
'test:coverage': 'pnpm test --coverage',
// 开发
dev: 'pnpm dev',
'dev:playground': 'pnpm dev:playground',
// 代码质量
lint: 'pnpm lint',
'lint:fix': 'pnpm lint --fix',
typecheck: 'pnpm typecheck',
// 发布
release: 'pnpm release',
'release:beta': 'pnpm release --tag beta',
}
// 项目结构
const projectStructure = {
packages: {
core: '核心引擎',
cli: '命令行工具',
vite: 'Vite 插件',
webpack: 'Webpack 插件',
nuxt: 'Nuxt 模块',
presets: '预设包',
transformers: '转换器',
},
playground: '在线演示',
examples: '示例项目',
docs: '文档',
test: '测试文件',
}
3. 贡献类型
// 贡献类型
const contributionTypes = {
// 代码贡献
code: {
bugFixes: '修复 Bug',
features: '新功能开发',
performance: '性能优化',
refactoring: '代码重构',
},
// 文档贡献
documentation: {
guides: '编写指南',
examples: '示例代码',
translation: '文档翻译',
apiDocs: 'API 文档',
},
// 社区贡献
community: {
support: '用户支持',
tutorials: '教程创作',
talks: '技术分享',
plugins: '插件开发',
},
// 测试贡献
testing: {
unitTests: '单元测试',
integrationTests: '集成测试',
e2eTests: '端到端测试',
bugReports: 'Bug 报告',
},
}
插件开发
1. 插件模板
// 插件开发模板
function createUnoPlugin(options = {}) {
return {
name: 'my-uno-plugin',
// 插件配置
configResolved(config) {
// 配置解析后的钩子
},
// 规则定义
rules: [
// 静态规则
['my-rule', { color: 'red' }],
// 动态规则
[/^my-(.+)$/, ([, value]) => ({ color: value })],
// 函数规则
[/^my-fn-(.+)$/, ([, value]) => {
if (isValidColor(value)) {
return { color: value }
}
}],
],
// 变体定义
variants: [
(matcher) => {
if (matcher.startsWith('my:')) {
return {
matcher: matcher.slice(3),
selector: s => `.my-context ${s}`,
}
}
return matcher
},
],
// 快捷方式
shortcuts: {
'my-btn': 'px-4 py-2 bg-blue-500 text-white rounded',
},
// 主题扩展
theme: {
colors: {
'my-primary': '#3b82f6',
},
},
// 预检样式
preflights: [
{
getCSS() {
return `
.my-base {
box-sizing: border-box;
}
`
},
},
],
// 后处理
postprocess(util) {
// 处理生成的工具类
return util
},
}
}
// 插件使用
export default defineConfig({
plugins: [
createUnoPlugin({
// 插件选项
}),
],
})
2. 插件发布
// package.json
{
"name": "unocss-plugin-my-plugin",
"version": "1.0.0",
"description": "My awesome UnoCSS plugin",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": [
"dist"
],
"keywords": [
"unocss",
"css",
"plugin",
"atomic-css"
],
"peerDependencies": {
"unocss": "^0.50.0"
},
"devDependencies": {
"unocss": "^0.50.0",
"typescript": "^4.9.0",
"unbuild": "^1.0.0"
},
"scripts": {
"build": "unbuild",
"dev": "unbuild --stub",
"test": "vitest",
"prepublishOnly": "pnpm build"
}
}
未来发展
路线图
// UnoCSS 发展路线图
const roadmap = {
// 短期目标 (3-6个月)
shortTerm: [
'性能进一步优化',
'更多预设和插件',
'IDE 支持增强',
'文档完善',
'社区生态建设',
],
// 中期目标 (6-12个月)
mediumTerm: [
'可视化设计工具',
'组件库集成',
'设计系统支持',
'多语言支持',
'企业级功能',
],
// 长期目标 (1-2年)
longTerm: [
'AI 辅助样式生成',
'跨平台支持',
'标准化推进',
'生态系统成熟',
'行业采用',
],
}
// 技术趋势
const techTrends = {
// CSS 技术发展
css: [
'CSS Container Queries',
'CSS Cascade Layers',
'CSS Color Functions',
'CSS Nesting',
'CSS Subgrid',
],
// 构建工具发展
buildTools: [
'Vite 生态',
'ESBuild 优化',
'SWC 集成',
'Turbopack 支持',
'Bun 兼容',
],
// 框架发展
frameworks: [
'Vue 3 Composition API',
'React Server Components',
'Svelte 5',
'Solid.js',
'Qwik',
],
}
社区参与
// 参与方式
const participationWays = {
// 开发者
developers: [
'贡献代码',
'报告 Bug',
'提出功能请求',
'编写测试',
'优化性能',
],
// 设计师
designers: [
'设计组件库',
'创建设计系统',
'提供设计指导',
'用户体验优化',
'视觉设计',
],
// 内容创作者
contentCreators: [
'编写教程',
'制作视频',
'翻译文档',
'技术分享',
'案例研究',
],
// 企业用户
enterprises: [
'提供反馈',
'赞助开发',
'分享最佳实践',
'企业级需求',
'生态建设',
],
}
本章总结
通过本章学习,我们全面了解了:
- 官方生态:核心包、工具、IDE支持
- 社区生态:预设、插件、扩展
- 学习资源:文档、教程、社区
- 贡献指南:如何参与开源贡献
- 未来发展:路线图和技术趋势
核心要点
- UnoCSS 拥有活跃的开源社区
- 丰富的工具和插件生态系统
- 多种学习资源和支持渠道
- 开放的贡献机制
- 明确的发展方向
下一步
在下一章中,我们将通过一个完整的实战项目来综合运用所学知识。
练习题
- 生态探索:调研并试用3个社区插件
- 工具配置:配置完整的开发环境
- 社区参与:在GitHub上提交一个Issue或PR
- 插件开发:开发一个简单的UnoCSS插件
- 知识分享:写一篇UnoCSS使用心得