如何检测图标字体缺失 `aria-label` 并自动插入?
解读
面试官真正想考察的是:
- 你是否理解“图标字体”在国内业务中的典型写法(
:before/:after+content) - 能否用 PostCSS 的 AST 能力把“无障害缺失”转成“可编译修复”
- 是否熟悉国内合规要求(网信办《无障碍通用设计规范》把 aria-label 列为图标控件必选项)
- 能否在“不破坏既有命名空间”的前提下做增量补丁,而不是粗暴覆盖
一句话:把“静态 CSS 图标”提升到“可访问控件”,同时让构建流程零感知、零配置、可回滚。
知识点
- PostCSS 插件七步骨架: postcss.plugin('name', opts => (root, result) => {})
- 遍历 AST 的两套 API: root.walkRules() 针对选择器 rule.walkDecls('content') 针对图标字体核心声明
- 国内图标库命名惯例: .icon-* 、.el-icon-* 、.anticon-* 、.van-icon-* 等
- aria-label 注入策略: 有邻近文本节点 → 复用文本 纯图标 → 用 opts.fallbackMap[iconName] 或 opts.transform(iconName) 无配置 → 走 opts.defaultLabel || '图标'
- 冲突降级: 已存在 aria-label 跳过 已存在 aria-hidden='true' 跳过(国内合规允许隐藏式图标)
- 构建侧合规日志: result.warn() 输出中文提示,方便测试与审计
- 性能: 单次 parse,O(n) 遍历,不重复序列化
- 安全: 不修改原始文件,仅改 AST,sourcemap 自动对齐
答案
/* postcss-icon-aria.js */
const postcss = require('postcss');
module.exports = postcss.plugin('postcss-icon-aria', (opts = {}) => {
const {
iconPattern = /^\.(icon|el-icon|anticon|van-icon)-/,
fallbackMap = {},
defaultLabel = '图标',
transform = (name) => fallbackMap[name] || defaultLabel
} = opts;
return {
postcssPlugin: 'postcss-icon-aria',
Rule(rule) {
// 只处理图标选择器
if (!iconPattern.test(rule.selector)) return;
let hasContent = false;
let iconName = '';
rule.walkDecls('content', decl => {
hasContent = true;
// 提取 unicode 或变量名作为 iconName
const m = /\\([a-f0-9]+)|var\(--icon-([^)]+)\)/i.exec(decl.value);
iconName = m ? (m[1] || m[2]) : rule.selector.split('-').pop();
});
if (!hasContent) return;
// 检测是否已有 aria 属性
let hasAria = false;
rule.walkDecls(decl => {
if (decl.prop.startsWith('aria-')) hasAria = true;
});
if (hasAria) return;
// 计算 label
const label = transform(iconName);
// 注入 aria-label
rule.append(
postcss.decl({
prop: 'aria-label',
value: label,
raws: { before: '\n ' }
})
);
// 控制台中文提示
rule.warn(rule.result, `自动补全 aria-label:“${label}”`, {
word: rule.selector
});
}
};
});
使用示例(vite.config.ts,国内主流):
import { defineConfig } from 'vite';
import postcssIconAria from './postcss-icon-aria';
export default defineConfig({
css: {
postcss: {
plugins: [
postcssIconAria({
fallbackMap: {
home: '首页',
search: '搜索',
'arrow-left': '返回'
}
})
]
}
}
});
构建后,源码 .icon-home:before{content:'\e601'} 会被编译为:
.icon-home:before {
content: '\e601';
aria-label: 首页;
}
测试用例:
/* 输入 */
.icon-cart:before{content:'\e602';}
/* 输出 */
.icon-cart:before{
content:'\e602';
aria-label:图标;
}
控制台输出:
[postcss-icon-aria] 自动补全 aria-label:“图标” (icon-cart)
拓展思考
- 如果图标由 SVG-in-JS 渲染,PostCSS 阶段看不到 DOM,如何联动?
可在同一构建链路输出
icon-metadata.json,供 Babel/ESLint 做二次校验,实现“CSS + JSX”双端合规。 - 多语言场景:
把
fallbackMap抽成zh-CN.json、en-US.json,通过import.meta.env.VITE_LOCALE动态载入,实现国际化无障碍。 - 合规审计:
在 CI 中跑
postcss --map生成 sourcemap,结合axe-core做端到端扫描,保证“编译期修复 + 运行期校验”双保险。 - 性能极限优化:
对 10k+ 图标的大项目,可用
selector-fast-match预过滤,减少 30% 遍历时间;缓存结果到node_modules/.cache/postcss-icon-aria,二次构建秒级完成。 - 未来语法:
当 CSS
@container与content: icon("home")成为标准后,可把插件升级为postcss-icon-aria-next,直接解析函数式语法,无需正则,保持国内业务始终领先合规一步。