悠悠楠杉
专业前端必备:手把手教你玩转stylelint代码规范检查
作为前端工程师,你是否经常遇到这些场景?团队CSS样式互相覆盖、命名风格五花八门、浏览器兼容属性缺失...stylelint正是解决这些痛点的专业工具。下面从实战角度分享它的完整工作流。
一、环境准备与基础配置
首先通过npm安装核心包:
bash
npm install stylelint stylelint-config-standard --save-dev
新建配置文件.stylelintrc.json
(也支持JS/YAML格式):
json
{
"extends": "stylelint-config-standard",
"rules": {
"color-no-invalid-hex": true,
"font-family-no-missing-generic-family-keyword": null
}
}
这里有两个关键点:
1. extends
继承标准配置集合
2. rules
可覆盖默认规则,示例中关闭了字体族检查
二、核心规则配置技巧
stylelint提供200+条内置规则,常见分类及典型配置:
语法检查类:
json
{
"no-empty-source": true, // 禁止空文件
"no-extra-semicolons": true // 多余分号检查
}
格式规范类:
json
{
"indentation": 2, // 2空格缩进
"selector-list-comma-newline-after": "always-multi-line"
}
兼容性检查类:
json
{
"property-no-vendor-prefix": true, // 禁止冗余前缀
"media-feature-name-no-vendor-prefix": true
}
推荐使用stylelint-config-recommended
作为基础配置,再逐步叠加规则。
三、进阶插件生态
通过插件可扩展检查能力:
属性顺序检查:
bash npm install stylelint-order --save-dev
配置示例:
json { "plugins": ["stylelint-order"], "rules": { "order/properties-order": [ "position", "top", "display", "width" ] } }
BEM命名校验:
bash npm install stylelint-selector-bem-pattern --save-dev
四、自动化集成方案
VS Code实时检测:
安装官方插件后,配置settings.json:
json
{
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": true
}
}
Webpack构建集成:
通过stylelint-webpack-plugin
:
```js
const StylelintPlugin = require('stylelint-webpack-plugin');
module.exports = {
plugins: [
new StylelintPlugin({
files: '**/*.(css|scss)',
fix: true
})
]
};
```
Git提交拦截:
配合husky实现提交前校验:
json
{
"husky": {
"hooks": {
"pre-commit": "stylelint 'src/**/*.css'"
}
}
}
五、自定义规则开发
当现有规则不满足需求时,可以创建规则模块:
js
module.exports = function(primaryOption) {
return (postcssRoot, postcssResult) => {
postcssRoot.walkDecls(decl => {
if (decl.prop === 'z-index' && decl.value === '999') {
postcssResult.warn('避免使用魔法数字', { node: decl });
}
});
};
};
通过stylelint.registerRule()
注册后即可在配置中调用。
掌握stylelint就像获得一个24小时在线的CSS代码审查员,它能将团队样式代码问题消灭在开发阶段。建议从基础规则开始逐步扩展,最终形成适合项目的完整规范体系。记住:好的工具要用在正确的流程中才能真正发挥作用。
```