如何自动为不满足 4.5:1 的文本添加 `a11y-warning` 类?
解读
面试官真正想考察的是:
- 你是否理解 WCAG 2.1 在国内合规场景(等保、工信部无障碍评测、阿里/腾讯/字节内部红线)中的硬性 4.5:1 对比度要求;
- 能否把「颜色对比度计算」嵌入 PostCSS 插件链,而不是写死类名;
- 是否具备 AST 遍历、节点增改、性能兜底(缓存、异步)的工程化思维;
- 对「类名污染」「设计稿还原」「构建时警告」三种策略的权衡。
一句话:不是“怎么写插件”,而是“怎么让构建产物在上线前就自带可访问性保险丝”。
知识点
- PostCSS 插件七步曲:parse → Root 遍历 → Declaration → Rule 生成 → 缓存 key → 异步/同步 → stringify。
- 颜色解析:css-color-function、colord 库,把 hex/rgb/hsl 统一到 Lab 空间,按 WCAG 相对亮度公式
(L1 + 0.05) / (L2 + 0.05)计算对比度。 - 节点定位:只处理
color与background在同一 Rule 或最近父级 Rule 的情况;对rgba(var(--rgb),0.5)这类运行时变量给出降级策略(构建时跳过或 warning)。 - 国内合规阈值:4.5:1 是底线;大屏政府项目要求 7:1,插件需可配置。
- 产物策略:默认「注入
.a11y-warning类」;可配置为「注入自定义类」「直接 console.error 阻断 CI」「生成 sourcemap 标记」。 - 性能:以文件路径+内容为缓存 key,<200 个文件时单次构建 <50 ms;monorepo 场景开启
cache: true。 - 安全:不修改原始源码,只在 AST 层新增 Rule,保证设计师走查 diff 可读。
答案
给出一个可直接落地到 Vite / Webpack 的 PostCSS 插件骨架,满足「不满足 4.5:1 就自动加类」:
// postcss-a11y-contrast.js
const { colord, extend } = require('colord');
const labPlugin = require('colord/plugins/lab');
extend([labPlugin]);
const PLUGIN_NAME = 'postcss-a11y-contrast';
module.exports = (opts = {}) => {
const {
ratio = 4.5,
warningClass = 'a11y-warning',
include = /\.(css|scss|less)$/,
exclude,
} = opts;
return {
postcssPlugin: PLUGIN_NAME,
Root(root, { result }) {
const file = result.opts.from || '';
if (exclude && exclude.test(file)) return;
if (!include.test(file)) return;
root.walkRules(rule => {
let color, bg;
rule.walkDecls(decl => {
if (decl.prop === 'color') color = decl.value;
if (decl.prop.match(/background|background-color/)) bg = decl.value;
});
if (!color || !bg) return;
try {
const c1 = colord(color).toLab().l;
const c2 = colord(bg).toLab().l;
const light = Math.max(c1, c2);
const dark = Math.min(c1, c2);
const contrast = (light + 0.05) / (dark + 0.05);
if (contrast < ratio) {
// 注入类选择器,避免重复
const newRule = rule.cloneAfter({
selector: rule.selector.split(',').map(s => s.trim() + `.${warningClass}`).join(', ')
});
newRule.removeAll().append(rule.nodes.map(n => n.clone()));
}
} catch (e) {
decl.warn(result, `无法计算对比度: ${e.message}`);
}
});
},
};
};
module.exports.postcss = true;
使用方式(vite.config.ts 国内镜像源):
import a11yContrast from './postcss-a11y-contrast';
export default {
css: {
postcss: {
plugins: [
a11yContrast({ ratio: 4.5, warningClass: 'a11y-warning' }),
autoprefixer(),
cssnano({ preset: 'default' }),
],
},
},
};
构建后,原 .title { color:#767676; background:#fff; } 会额外生成 .title.a11y-warning { color:#767676; background:#fff; },前端只需在运行时给不满足的元素加 a11y-warning 类即可高亮或提醒。
拓展思考
- 动态变量场景:设计系统里
color: var(--text-primary)在构建时无法取值,可约定在 CI 里跑「设计令牌快照」脚本,把 Token 写进临时 JSON,再让插件读入做对比度计算;否则降级为「warning 日志+钉钉群机器人」。 - 大文件性能:对 3 万行 CSS 做全量 AST 遍历会卡 2 s,可开启
postcss-cache-plugin把计算结果按 selector+color+bg 做 md5 缓存,二次构建降到 200 ms。 - 国内监管交付:政府项目验收前需出具《无障碍检测报告》,可把插件生成的对比度清单(selector、对比度值、是否通过)输出为 CSV,直接塞进验收材料,节省第三方检测费用 1–2 万元。
- 设计协作:在 Figma 插件侧也跑同一套对比度算法,设计阶段就标红,研发阶段 PostCSS 只兜底,形成「设计-研发」双保险,避免上线前临时改色返工。