如何提示将动画方向抽象为变量?
解读
面试官抛出“如何提示将动画方向抽象为变量”,并不是想听你背诵“把 normal 换成 var(--direction)”这么简单。
在国内一线前端团队的真实评审场景里,这道题考察的是“能否用 Stylelint 把‘写死动画方向’识别为代码坏味道,并给出可落地的修复方案”。
核心诉求有三点:
- 规则必须能精准命中方向关键字(normal、reverse、alternate、alternate-reverse),避免误杀其他属性。
- 提示信息要让开发者一眼看懂“该抽变量”,而不是“该删代码”。
- 自动修复不能破坏现有逻辑,最好一步到位生成 var() 调用,并附带变量命名建议。
知识点
- Stylelint 规则三大件:
- selector / prop 匹配器(regex 或 AST)
- report({ message, word, fix }) 上报
- 可选的 fix() 回调返回 PostCSS 补丁
- PostCSS 遍历钩子:
- Declaration → prop 为 animation 或 animation-direction 时进入
- valueParser 拆 value 节点,识别 <single-animation-direction> 位置
- 变量命名策略:
- 统一前缀 --anim-dir-
- 按组件作用域降级::root → 组件 → 局部
- 国内规范落地经验:
- 与 Design Token 仓库对齐,变量值走主题系统
- 配套 eslint-css-modules 防止 var 名拼写错
- CI 阶段加 --fix-dry-run 统计“方向硬编码”次数,计入质量红线
答案
- 本地插件目录 stylelint-plugins/animation-direction-var/index.js
const { createPlugin } = require('stylelint');
const valueParser = require('postcss-value-parser');
const ruleName = 'plugin/animation-direction-var';
const messages = createPlugin.ruleMessages(ruleName, {
expected: (dir) => `动画方向 "${dir}" 请抽象为变量,如 var(--anim-dir-${dir})`,
});
const DIRECTION_KEYWORDS = ['normal', 'reverse', 'alternate', 'alternate-reverse'];
function hasHardcodedDirection(value) {
const nodes = valueParser(value).nodes;
for (const node of nodes) {
if (node.type === 'word' && DIRECTION_KEYWORDS.includes(node.value)) {
return node.value;
}
}
return null;
}
const plugin = createPlugin(ruleName, (primary, _, context) => (root, result) => {
root.walkDecls(decl => {
if (!['animation', 'animation-direction'].includes(decl.prop)) return;
const bad = hasHardcodedDirection(decl.value);
if (!bad) return;
if (context.fix) {
const newValue = decl.value.replace(
new RegExp(`\\b${bad}\\b`),
`var(--anim-dir-${bad})`
);
decl.value = newValue;
return;
}
createPlugin.report({
message: messages.expected(bad),
node: decl,
word: bad,
result,
ruleName,
});
});
});
plugin.ruleName = ruleName;
plugin.messages = messages;
module.exports = plugin;
- 在 stylelint.config.js 中注册
module.exports = {
plugins: ['./stylelint-plugins/animation-direction-var'],
rules: {
'plugin/animation-direction-var': [true, { severity: 'warning' }],
},
};
- 运行
npx stylelint "**/*.scss" --fix
硬编码的 normal / reverse 会被自动替换成 var(--anim-dir-normal) 等,同时终端给出中文提示。
若变量未定义,可再配合 stylelint-declaration-strict-value 进行二次校验,保证变量真实存在。
拓展思考
- 方向变量与主题切换:
夜间模式往往需要把 alternate 反向,抽成变量后,只需在 :root[data-theme='dark'] 里重定义 --anim-dir-alternate 即可,无需重写整条 animation。 - 与 Tailwind / UnoCSS 共存:
原子化框架会把动画封装成类,如 animate-ping。此时规则要加一层判断:若父选择器已含 animate-* 类名,则跳过校验,避免误报。 - 性能与可读性权衡:
抽变量会增加 CSS 体积(多声明一次),但换来可维护性与缓存命中率。国内大厂实践表明,方向类变量 gzip 后增量 <0.3%,可接受。 - 未来演进:
把变量命名规则收敛到 Design Token 标准后,可进一步写 stylelint 插件自动生成 token 文档,实现“代码即文档”,让 UI 走查与研发共用同一套方向语义。