主题
处理器
🌐 Processors
处理器是用来转换生成的 CSS 的钩子。它们不同于在提取前修改源代码的变换器,处理器是在 UnoCSS 生成完 CSS 层之后运行的。
🌐 Processors are hooks that transform generated CSS. Unlike transformers, which modify source code before extraction, processors run after UnoCSS has generated its CSS layers.
定义一下处理器
🌐 Define a processor
一个处理器接收某一层的 CSS,然后返回应该替换它的 CSS。支持同步和异步结果。
🌐 A processor receives the CSS for one layer and returns the CSS that should replace it. Both synchronous and asynchronous results are supported.
ts
import type { CSSProcessor } from '@unocss/core'
import { defineConfig } from 'unocss'
const banner: CSSProcessor = {
name: 'add-banner',
order: 10,
process(css, { layer, envMode }) {
if (envMode !== 'build')
return css
return `/* generated layer: ${layer} */\n${css}`
},
}
export default defineConfig({
processors: [banner],
})处理流程
🌐 Processing flow
对于每个非空的 CSS 层,UnoCSS 会执行以下步骤:
🌐 For every non-empty CSS layer, UnoCSS performs these steps:
- 生成原始层 CSS,包括预设样式和任何已启用的 CSS 层封装器或层标记。
- 按
order升序排列处理器。 - 让这一层依次通过每个处理器。一个处理器的输出就成为下一个处理器的输入。
- 缓存处理过的层,并通过
getLayer()、getLayers()和css暴露出来。
不同的层可以同时处理。处理器应该避免依赖层之间共享的可变状态。
🌐 Different layers may be processed concurrently. A processor should avoid relying on mutable state shared between layers.
当 setLayer() 更改一个层时,它的回调会收到原始的、未处理的 CSS。然后 UnoCSS 会再次将更新后的 CSS 通过完整的处理器链运行。这可以防止处理器对自己之前的输出重复应用。
🌐 When setLayer() changes a layer, its callback receives the raw, unprocessed CSS. UnoCSS then runs the updated CSS through the complete processor chain again. This prevents processors from being applied repeatedly to their own previous output.
text
generated layer
-> processor 1
-> processor 2
-> processed layer output如果处理器抛出错误,生成就会失败,错误会传递给调用者。
🌐 If a processor throws an error, generation fails and the error is passed to the caller.
上下文
🌐 Context
传给 process() 的第二个参数是一个 CSSProcessorContext:
🌐 The second argument passed to process() is a CSSProcessorContext:
ts
interface CSSProcessorContext<Theme extends object = object> {
layer: string
theme: Theme
envMode: 'dev' | 'build'
}layer是当前生成的图层的名称。theme是已解析的 UnoCSS 主题。envMode表示 UnoCSS 是在为开发环境还是生产环境生成 CSS。
处理器顺序
🌐 Processor order
拥有较低 order 的处理器先运行。没有明确顺序的处理器使用 0。
🌐 Processors with a lower order run first. Processors without an explicit order use 0.
ts
processors: [
{ name: 'minify', order: 20, process: minify },
{ name: 'prefix', order: 10, process: addPrefixes },
]在这个例子中,prefix 在 minify 之前运行。
🌐 In this example, prefix runs before minify.
由预设和用户配置声明的处理器会被合并。当重复的处理器被移除时,处理器 name 会识别它。
🌐 Processors declared by presets and the user configuration are merged. The processor name identifies it when duplicate processors are removed.
官方处理器
🌐 Official processors