Stylelint 详细配置指南
一、什么是 Stylelint?
Stylelint 是一款开源的 CSS 代码检查工具,核心定位是「CSS 的 ESLint」,主要作用:
- 检测 CSS/SCSS/LESS 等样式文件中的语法错误、潜在问题(如无效属性、重复选择器);
- 强制统一样式编码规范(如缩进、命名、属性顺序);
- 支持自定义规则、插件,适配不同技术栈(Vue/React/PostCSS 等);
- 提供自动修复功能,解决大部分格式类问题;
- 支持 CSS 预处理器(SCSS/LESS/Sass)、CSS-in-JS、Vue 单文件组件等。
核心优势
- 全面的规则覆盖:内置 170+ 规则,覆盖语法、格式、最佳实践;
- 多语法支持:原生支持 CSS、SCSS、LESS、PostCSS、CSS Modules 等;
- 自动修复:多数规则支持
--fix自动修复; - 生态丰富:大量第三方插件(如 stylelint-scss、stylelint-order);
- 集成友好:可与 VS Code、Webpack、lint-staged、CI/CD 无缝集成。
二、安装与基础配置
2.1 局部安装(推荐)
适用于单个项目,避免全局版本冲突:
# 初始化 package.json(若未初始化)
npm init -y
# 安装 Stylelint 核心依赖
npm install stylelint --save-dev
# 安装官方推荐规则集(必装,提供基础规则)
npm install stylelint-config-standard --save-dev
# 解析 Vue/HTML 中 <style> 标签,让 Stylelint 识别模板内样式
npm install stylelint-config-html --save-dev
# Vue 推荐规则集(适配 Vue SFC 特性,如 scoped、v-deep 等)
npm install stylelint-config-recommended-vue --save-dev
# 若使用 SCSS,安装 SCSS 专用规则集和解析器
npm install stylelint-config-standard-scss stylelint-scss --save-dev
# 若使用 LESS,安装 LESS 专用插件
npm install stylelint-less --save-dev
2.2 初始化配置文件
Stylelint 支持多种配置文件格式,优先级:
stylelint.config.js > .stylelintrc.js > .stylelintrc.json > .stylelintrc.yml > package.json 中的 stylelint 字段
方式 1:创建 stylelint.config.js(推荐,支持注释/动态逻辑)
// 基础 CSS 配置示例
module.exports = {
// 1. 扩展已有的规则集
extends: [
'stylelint-config-standard' // 官方推荐的 CSS 标准规则集
],
// 2. 自定义规则(优先级高于 extends)
rules: {
// 规则格式:"规则名": [规则值, 规则选项]
// 规则值:null(禁用)/ "warning"(警告)/ "error"(错误)
'indentation': 2, // 缩进 2 个空格
'string-quotes': 'single', // 强制使用单引号
'no-empty-source': null, // 禁用「空文件」检查规则
'color-hex-length': 'short', // 十六进制颜色值强制简写(#fff 而非 #ffffff)
'declaration-block-trailing-semicolon': 'always' // 声明块末尾强制加分号
},
// 3. 指定文件解析器(默认无需配置,自动推断)
customSyntax: null,
// 4. 忽略文件/目录
ignoreFiles: [
'node_modules/**/*',
'dist/**/*',
'*.min.css'
]
};
方式 2:SCSS 配置示例
module.exports = {
extends: [
'stylelint-config-standard-scss' // SCSS 标准规则集
],
plugins: [
'stylelint-scss' // SCSS 专用插件
],
rules: {
// SCSS 自定义规则
'scss/at-rule-no-unknown': true, // 禁止未知的 SCSS @ 规则
'scss/no-duplicate-dollar-variables': 'error', // 禁止重复的 $ 变量
'scss/selector-no-redundant-nesting-selector': 'error' // 禁止冗余的嵌套选择器 &
},
ignoreFiles: [
'node_modules/**/*',
'dist/**/*'
]
};
方式 3:Vue 文件配置示例
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-config-recommended-vue' // Vue 专用规则集
],
// 指定 Vue 文件解析器
customSyntax: 'postcss-html',
rules: {
// 适配 Vue 的规则调整
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['deep', 'global'] // 忽略 Vue 的 ::v-deep/::v-global
}
]
},
ignoreFiles: [
'node_modules/**/*',
'dist/**/*'
]
};
三、核心配置项详解
3.1 核心配置字段
| 配置项 | 类型 | 说明 | 示例 |
|---|---|---|---|
extends | Array/String | 继承已有的规则集(可继承多个,后继承的覆盖先继承的) | extends: ['stylelint-config-standard', 'stylelint-config-prettier'] |
plugins | Array | 引入第三方插件(插件名可省略 stylelint-plugin- 前缀) | plugins: ['stylelint-scss', 'stylelint-order'] |
rules | Object | 自定义规则(覆盖 extends 中的规则) | rules: { 'indentation': 2 } |
customSyntax | String/Function | 指定自定义语法解析器(用于非标准 CSS 语法) | customSyntax: 'postcss-scss'(SCSS)/ postcss-html(Vue) |
ignoreFiles | Array | 指定忽略检查的文件/目录(支持 glob 通配符) | ignoreFiles: ['node_modules/**/*', '*.min.css'] |
defaultSeverity | String | 默认规则级别(warning/error),默认 error | defaultSeverity: 'warning' |
reportInvalidScopeDisables | Boolean | 报告无效的 /* stylelint-disable */ 注释 | reportInvalidScopeDisables: true |
reportNeedlessDisables | Boolean | 报告不必要的 /* stylelint-disable */ 注释 | reportNeedlessDisables: true |
3.2 常用核心规则详解
Stylelint 规则分为 6 大类:语法检查、格式规范、最佳实践、命名规范、属性顺序、插件扩展。以下是高频使用的核心规则:
3.2.1 格式规范类(可自动修复)
| 规则名 | 默认值 | 说明 | 示例 |
|---|---|---|---|
indentation | 2 | 缩进空格数 | 'indentation': 2(2 个空格)/ 'indentation': 'tab'(Tab) |
string-quotes | "double" | 字符串引号规则 | 'string-quotes': 'single'(强制单引号) |
declaration-block-trailing-semicolon | "always" | 声明块末尾是否加分号 | 'declaration-block-trailing-semicolon': 'always'(强制加) |
block-closing-brace-newline-after | "always" | 块闭合大括号后是否换行 | 'block-closing-brace-newline-after': 'always' |
selector-list-comma-newline-after | "always" | 选择器列表逗号后是否换行 | 'selector-list-comma-newline-after': 'always' |
color-hex-case | "lower" | 十六进制颜色值大小写 | 'color-hex-case': 'lower'(强制小写) |
color-hex-length | "short" | 十六进制颜色值长度 | 'color-hex-length': 'short'(简写 #fff 而非 #ffffff) |
3.2.2 语法检查类(不可自动修复)
| 规则名 | 默认值 | 说明 | 示例 |
|---|---|---|---|
no-empty-source | true | 禁止空文件 | 'no-empty-source': null(禁用) |
no-invalid-double-slash-comments | true | 禁止无效的双斜杠注释(CSS 仅支持 /* */ 注释) | 'no-invalid-double-slash-comments': true |
property-no-unknown | true | 禁止未知的 CSS 属性 | 'property-no-unknown': [true, { ignoreProperties: ['custom-prop'] }] |
selector-pseudo-class-no-unknown | true | 禁止未知的伪类选择器 | 'selector-pseudo-class-no-unknown': [true, { ignorePseudoClasses: ['deep'] }] |
at-rule-no-unknown | true | 禁止未知的 @ 规则 | 'at-rule-no-unknown': [true, { ignoreAtRules: ['extend'] }](SCSS 需忽略) |
3.2.3 最佳实践类
| 规则名 | 默认值 | 说明 | 示例 |
|---|---|---|---|
no-duplicate-selectors | true | 禁止重复的选择器 | 'no-duplicate-selectors': 'error' |
no-duplicate-properties | true | 禁止重复的属性 | 'no-duplicate-properties': [true, { ignore: ['consecutive-duplicates-with-different-values'] }] |
no-extra-semicolons | true | 禁止多余的分号 | 'no-extra-semicolons': 'error' |
declaration-block-no-shorthand-property-overrides | true | 禁止简写属性覆盖具体属性 | 'declaration-block-no-shorthand-property-overrides': 'error' |
value-no-vendor-prefix | false | 禁止浏览器前缀(建议用 autoprefixer) | 'value-no-vendor-prefix': [true, { ignoreValues: ['webkit-box'] }] |
3.3 SCSS 专用规则(stylelint-scss)
需先安装 stylelint-scss 插件,常用规则:
| 规则名 | 说明 | 示例 |
|---|---|---|
scss/at-rule-no-unknown | 禁止未知的 SCSS @ 规则 | 'scss/at-rule-no-unknown': 'error' |
scss/no-duplicate-dollar-variables | 禁止重复的 $ 变量 | 'scss/no-duplicate-dollar-variables': 'error' |
scss/selector-no-redundant-nesting-selector | 禁止冗余的 & 嵌套选择器 | 'scss/selector-no-redundant-nesting-selector': 'error' |
scss/dollar-variable-no-missing-interpolation | 禁止 $ 变量未插值使用 | 'scss/dollar-variable-no-missing-interpolation': 'warning' |
scss/comment-no-empty | 禁止空注释 | 'scss/comment-no-empty': 'error' |
3.4 属性顺序规则(stylelint-order)
安装插件:
npm install stylelint-order --save-dev
配置示例:
module.exports = {
plugins: ['stylelint-order'],
rules: {
// 强制属性按指定顺序排列
'order/properties-order': [
// 布局属性优先
'position',
'top',
'right',
'bottom',
'left',
'z-index',
// 盒模型属性
'display',
'float',
'width',
'height',
'margin',
'padding',
// 样式属性
'background',
'color',
'font',
'text-align'
],
// 或按属性组排序
'order/declaration-block-properties-group-order': [
'layout',
'box-model',
'typography',
'visual',
'animation',
'misc'
]
}
};
四、忽略文件:.stylelintignore
与 .gitignore 语法一致,指定不需要检查的文件/目录,示例:
# 忽略 node_modules 目录
node_modules/
# 忽略打包产物
dist/
build/
out/
# 忽略压缩后的 CSS 文件
*.min.css
# 忽略特定目录
src/assets/css/vendor/
# 忽略 Vue 编译后的文件
src/components/generated/
五、常用命令
5.1 检查文件/目录
# 局部安装时执行
npx stylelint src/styles/
# 检查指定类型文件
npx stylelint "src/**/*.{css,scss,vue}"
# 全局安装时执行
stylelint src/styles/
5.2 自动修复可修复问题
# 修复指定目录下的文件
npx stylelint src/styles/ --fix
# 修复单个文件
npx stylelint src/styles/index.scss --fix
⚠️ 注意:--fix 仅修复格式类规则(如缩进、引号、分号),语法错误需手动修复。
5.3 输出检查结果为指定格式
# 输出为 JSON 格式(CI/CD 集成)
npx stylelint src/styles/ --custom-formatter json
# 输出为详细的控制台格式
npx stylelint src/styles/ --custom-formatter stylish
# 仅输出错误(忽略警告)
npx stylelint src/styles/ --quiet
5.4 指定配置文件
# 自定义配置文件路径
npx stylelint src/styles/ --config .stylelintrc.custom.js
六、集成到开发流程
6.1 VS Code 集成(实时检查+自动修复)
- 安装 Stylelint 插件:在扩展市场搜索「Stylelint」(作者:Stylelint);
- 配置 VS Code 设置(settings.json):
{
// 启用 Stylelint 自动检查
"stylelint.enable": true,
// 保存时自动修复 Stylelint 问题
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": true
},
// 指定 Stylelint 检查的文件类型
"stylelint.validate": [
"css",
"scss",
"less",
"vue",
"html"
],
// 忽略的文件/目录
"stylelint.ignoreFiles": [
"**/node_modules/**",
"**/dist/**",
"*.min.css"
]
}
6.2 与 lint-staged 集成(提交前检查)
结合 husky + lint-staged,实现提交代码前自动检查样式文件:
// package.json
{
"lint-staged": {
"*.{css,scss,less,vue}": [
"stylelint --fix",
"git add"
]
}
}
6.3 Webpack 集成
使用 stylelint-webpack-plugin 实现打包时检查样式文件:
- 安装依赖:
npm install stylelint-webpack-plugin --save-dev
- 配置 webpack.config.js:
const StylelintPlugin = require('stylelint-webpack-plugin');
module.exports = {
plugins: [
new StylelintPlugin({
// 检查的文件
files: ['src/**/*.{css,scss,vue}'],
// 自动修复
fix: true,
// 忽略的文件
exclude: 'node_modules',
// 输出格式
formatter: 'stylish',
// 仅输出错误
quiet: true
})
]
};
6.4 Vue 项目集成
- 安装依赖:
npm install stylelint-config-recommended-vue postcss-html --save-dev
- 配置 stylelint.config.js:
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-config-recommended-vue/scss' // Vue + SCSS 规则集
],
customSyntax: 'postcss-html', // 解析 Vue 文件中的样式
rules: {
// 适配 Vue 的深度选择器
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['deep', 'global', 'v-deep']
}
],
// 允许 Vue 中的 scoped 属性
'selector-pseudo-element-no-unknown': [
true,
{
ignorePseudoElements: ['v-scope']
}
]
}
};
6.5 React 项目集成(CSS Modules)
- 安装依赖:
npm install stylelint-config-css-modules --save-dev
- 配置 stylelint.config.js:
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-config-css-modules' // 适配 CSS Modules
],
rules: {
// 允许 CSS Modules 的命名规则
'selector-class-pattern': [
'^[a-z][a-zA-Z0-9]+$',
{
message: '类名必须以小写字母开头,由字母和数字组成'
}
]
}
};
七、常见问题与解决方案
7.1 Stylelint 与 Prettier 规则冲突
现象:Prettier 格式化后的代码触发 Stylelint 报错(如缩进、引号)。
解决方案:安装 stylelint-config-prettier 禁用冲突规则:
npm install stylelint-config-prettier --save-dev
配置 stylelint.config.js:
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-config-prettier' // 放在最后,禁用冲突规则
]
};
7.2 SCSS 中 @extend 报 at-rule-no-unknown 错误
现象:SCSS 中使用 @extend 被 Stylelint 判定为未知 @ 规则。
解决方案:
module.exports = {
plugins: ['stylelint-scss'],
rules: {
// 禁用原生 at-rule-no-unknown,启用 SCSS 版本
'at-rule-no-unknown': null,
'scss/at-rule-no-unknown': 'error'
}
};
7.3 Vue 文件中样式检查不生效
现象:Vue 文件的 <style> 标签未触发 Stylelint 检查。
解决方案:
- 安装
postcss-html:npm install postcss-html --save-dev; - 配置
customSyntax: 'postcss-html'; - VS Code 中启用 Vue 文件验证:
"stylelint.validate": ["vue"]。
7.4 忽略特定行/块的检查
需求:部分代码无需 Stylelint 检查(如第三方样式覆盖)。
解决方案:使用注释禁用规则:
/* stylelint-disable */
/* 整个文件禁用 */
body { margin: 0 !important; }
/* stylelint-enable */
/* 禁用单行 */
body { margin: 0 !important; /* stylelint-disable-line declaration-no-important */ }
/* 禁用特定规则块 */
/* stylelint-disable declaration-no-important */
body { margin: 0 !important; }
/* stylelint-enable declaration-no-important */
7.5 规则过于严格,需要放宽
现象:团队不需要严格的规则(如允许空行、允许大写颜色值)。
解决方案:自定义规则降级为 warning 或禁用:
module.exports = {
rules: {
'color-hex-case': 'warning', // 降级为警告
'block-no-empty': null, // 禁用规则
'indentation': [2, { ignore: ['value'] }] // 忽略值的缩进检查
}
};
7.6 版本兼容问题
现象:Stylelint v15+ 与旧规则集不兼容。
原因:Stylelint v15+ 移除了旧版规则,需升级规则集。
解决方案:
# 升级规则集到最新版
npm install stylelint-config-standard@latest stylelint-config-standard-scss@latest --save-dev
八、常用插件与规则集
8.1 官方/主流插件
| 插件名 | 适用场景 | 说明 |
|---|---|---|
stylelint-scss | SCSS 项目 | 提供 SCSS 专用规则和解析器 |
stylelint-less | LESS 项目 | 提供 LESS 专用规则 |
stylelint-order | 所有项目 | 强制属性按指定顺序排列 |
stylelint-config-prettier | 所有项目 | 禁用与 Prettier 冲突的规则 |
stylelint-config-css-modules | CSS Modules 项目 | 适配 CSS Modules 语法 |
stylelint-config-rational-order | 所有项目 | 按逻辑顺序排列属性(布局→盒模型→样式) |
stylelint-declaration-block-no-ignored-properties | 所有项目 | 检测无效的属性组合(如 display: inline 搭配 width) |
8.2 主流规则集
| 规则集名称 | 适用场景 | 特点 |
|---|---|---|
stylelint-config-standard | 标准 CSS 项目 | 官方推荐,覆盖基础 CSS 规则 |
stylelint-config-standard-scss | SCSS 项目 | 标准 CSS 规则 + SCSS 专用规则 |
stylelint-config-recommended | 所有项目 | 仅包含必要的错误检查规则(无格式规则) |
stylelint-config-recommended-vue | Vue 项目 | 适配 Vue 单文件组件的推荐规则 |
stylelint-config-airbnb | 企业级项目 | Airbnb 样式规范,严格且全面 |
九、自定义规则开发(进阶)
9.1 基础自定义规则示例
创建自定义规则文件 rules/no-custom-property.js:
module.exports = {
meta: {
fixable: true, // 是否支持自动修复
messages: {
forbidden: '禁止使用自定义属性 --{{prop}}'
}
},
create(context) {
return {
// 监听属性声明
declaration(decl) {
if (decl.prop.startsWith('--')) {
context.report({
node: decl,
messageId: 'forbidden',
data: { prop: decl.prop },
// 自动修复逻辑
fix: (fixer) => fixer.remove(decl)
});
}
}
};
}
};
9.2 配置自定义规则
// stylelint.config.js
module.exports = {
plugins: [
// 引入自定义规则插件
{
rules: {
'no-custom-property': require('./rules/no-custom-property.js')
}
}
],
rules: {
'no-custom-property': 'error'
}
};
十、参考资料
- Stylelint 官方文档:https://stylelint.io/
- Stylelint 规则列表:https://stylelint.io/user-guide/rules/
- Stylelint SCSS 插件:https://github.com/stylelint-scss/stylelint-scss
- Stylelint Order 插件:https://github.com/hudochenkov/stylelint-order
- Stylelint 配置指南:https://stylelint.io/user-guide/configure/