如何限制滑块输出的数值必须在 4 的倍数?
解读
面试官把“滑块”与“Stylelint”放在同一语境,是在考察候选人能否把“UI 组件的数值约束”抽象成“样式代码的静态规则”。
在国内前端团队的真实面试里,这类问题常被包装成“业务需求 → 技术规则”的转化题:
- 滑块最终输出的是 CSS 数值(如 width、height、padding、border-radius 等);
- 业务要求该数值必须是 4 的倍数,以保证 4 pt 栅格系统;
- 靠人工 code review 成本高,必须用 Stylelint 自动化兜底。
因此,考点不是“如何写滑块”,而是“如何写一条 Stylelint 自定义规则,让任何手写或编译生成的 CSS 里,凡是受滑块影响的数值都必须满足 4 的倍数,否则报错并可自动修复”。
知识点
- Stylelint 规则结构:ruleName、primaryOption、secondaryOption、message、fix。
- PostCSS AST 遍历:Declaration → value → number + unit。
- 正则提取数值:/^(-?\d+)(\D*)$/。
- 数值整除算法:num % 4 === 0。
- 自动修复:node.value = 合法值 + 原单位。
- 国内大厂 4 pt 栅格规范:4、8、12、16、20…。
- 插件发布与接入:npm 私有仓 + .stylelintrc.js 配置。
- 与 Webpack/Vite 热更新集成,实现“滑块拖完即报错”。
答案
-
初始化插件
在公司私有 npm 仓库创建包 @x/stylelint-plugin-4pt,目录结构:
lib/rules/declaration-4pt-multiple.js
lib/index.js -
编写规则核心代码
// lib/rules/declaration-4pt-multiple.js
const { utils } = require('stylelint');
const ruleName = 'x/declaration-4pt-multiple';
const messages = utils.ruleMessages(ruleName, {
rejected: (value) => `值 "${value}" 必须是 4 的倍数,以符合栅格规范`,
});
const rule = (primary, secondary = {}) => (root, result) => {
const validProperties = secondary.properties || ['width', 'height', 'padding', 'margin', 'border-radius'];
const autoFix = secondary.autoFix !== false;
root.walkDecls((decl) => {
if (!validProperties.includes(decl.prop)) return;
const match = decl.value.match(/^(-?\d+)(\D*)$/);
if (!match) return;
const num = Number(match[1]);
const unit = match[2];
if (num % 4 !== 0) {
if (autoFix && context.fix) {
const fixed = Math.round(num / 4) * 4;
decl.value = fixed + unit;
return;
}
utils.report({
message: messages.rejected(decl.value),
node: decl,
result,
ruleName,
});
}
});
};
rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;
- 注册插件
// lib/index.js
module.exports = [require('./rules/declaration-4pt-multiple')];
- 接入工程
npm i -D @x/stylelint-plugin-4pt
.stylelintrc.js
module.exports = {
plugins: ['@x/stylelint-plugin-4pt'],
rules: {
'x/declaration-4pt-multiple': [true, { properties: ['width', 'height'], autoFix: true }],
},
};
- 脚本命令
"scripts": {
"lint:css": "stylelint \"src/**/*.{css,scss}\" --fix"
}
CI 阶段(GitHub Actions 或 GitLab CI)执行 npm run lint:css,若滑块生成的样式不满足 4 的倍数,直接阻断 MR。
拓展思考
- 动态变量场景:滑块输出的是 CSS 变量 --slider-value: 13px;规则需递归解析 var() 并计算最终值,可借助 postcss-custom-properties 插件先展开再校验。
- 响应式断点:在媒体查询内同样要遵守 4 的倍数,可把 walkDecls 换成 walkRules 深度优先。
- 非 px 单位:rem、rpx、vw 均需统一换算成 px 后再取模,可引入 postcss-px-to-viewport 的逆运算。
- 性能优化:对 10 万行样式的大型中台项目,用 postcss-selector-parser 提前过滤无关节点,减少 AST 遍历耗时。
- 规则分级:warn 级别给 UI 组件库,error 级别给业务代码,通过 secondary 的 severity 字段控制,避免阻塞组件库发版。
- 国内监管合规:金融类 App 需通过工信部 421 检测,样式错位会被视为“UI 异常”,用此规则可提前消除 1 px 误差导致的合规风险。