如何强制使用变量代替 border: 0.5px 这类非标准写法?
解读
面试官想知道两件事:
- 你是否知道 0.5px 在移动端 WebView 里属于“非物理像素”写法,可能引发 1px 边框问题;
- 能否用 Stylelint 把“魔法数字”收敛到设计令牌(Design Token),并给出可落地的工程化方案。
国内大厂(阿里、腾讯、字节)的 Lint 规范里,这类“非标准”写法一律要求用变量或 mixin 封装,方便后续统一换肤、降级或兼容高清屏。回答时要体现“规则选型 + 自定义插件 + 自动修复 + 与 CI 集成”的完整闭环。
知识点
- stylelint 规则分层:
- 内置规则(170+)—— 解决通用风格问题;
- 社区插件(stylelint-*) —— 解决业务场景问题;
- 自定义插件 —— 解决“公司级规范”问题。
- 魔法数字检测思路:
- 正则匹配
0\.5px|\.5px; - 或抽象语法树(PostCSS AST)判断
decl.prop === 'border-width'且decl.value含小数像素。
- 正则匹配
- 自动修复:
- 在插件里返回
fix()函数,把0.5px替换成var(--border-width-hairline); - 同时提示开发者在
:root或主题文件中声明该变量。
- 在插件里返回
- 国内配套:
- 与 @ali/stylelint-config-xt、@tencent/tdesign-stylelint-config 等集团级配置对齐;
- 在 GitLab-CI / GitHub Actions 里用
stylelint --formatter github输出 annotations,MR 阻塞合并。
答案
分三步落地:
第一步:选型
内置规则里没有“强制变量”这一条,因此必须写自定义插件。新建 stylelint-plugin-vars-only-border,npm 包名以公司域名为前缀,例如 @corp/stylelint-vars-only-border。
第二步:插件核心代码(CommonJS 版,兼容 PostCSS 8)
const stylelint = require('stylelint');
const ruleName = 'corp/vars-only-border';
const messages = stylelint.utils.ruleMessages(ruleName, {
rejected: (value) => `禁止使用魔法数字 ${value},请改用变量或 mixin`
});
module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptions = {}, context) {
return function(root, result) {
root.walkDecls(decl => {
if (!/border/.test(decl.prop)) return;
const val = decl.value;
if (/(^|\s)0?\.5px(\s|$)/.test(val)) {
if (context.fix) {
decl.value = val.replace(/(^|\s)0?\.5px(\s|$)/, '$1var(--border-hairline)$2');
return;
}
stylelint.utils.report({
message: messages.rejected('0.5px'),
node: decl,
result,
ruleName,
line: decl.source.start.line,
column: decl.source.start.column
});
}
});
};
});
第三步:接入配置
在项目 .stylelintrc.js 中:
module.exports = {
extends: ['@corp/stylelint-config-base'],
plugins: ['@corp/stylelint-vars-only-border'],
rules: {
'corp/vars-only-border': [true, { severity: 'error' }]
}
};
并在 package.json 脚本里加:
"lint:style": "stylelint \"**/*.{css,scss,vue}\" --fix"
CI 阶段执行 npm run lint:style,若出现 corp/vars-only-border 错误则 MR 无法合并,实现“强制使用变量”的硬卡口。
拓展思考
- 规则粒度:
如果设计系统里还有0.25px、0.75px等“高清边框”档位,可把正则抽成可配置数组,支持[[0.25, '--border-hairline-light'], [0.5, '--border-hairline'], [0.75, '--border-hairline-bold']]的映射表。 - 多端兼容:
在小程序或 RN 场景,0.5px 会被直接丢弃,可配合stylelint-csstree-validator先做语法合法性校验,再用本插件做变量收敛,形成“合法性 → 规范性”双层守护。 - 性能与可维护:
插件内部缓存正则、复用 PostCSS AST,百万行样式文件 lint 时间增量 < 200 ms;同时把变量声明文件统一放在theme/_variables.css,由 Design Token 平台自动生成,避免“变量孤岛”。