Vue 3 项目配置 Stylelint 的核心目标是统一 CSS/SCSS/Vue 样式规范,防止低级错误、保证属性排序、规避兼容性问题;它专注样式校验而非格式化,需安装 stylelint 及配套解析器、插件与规则集,并通过配置文件、忽略文件和 husky+lint-staged 集成到开发与提交流程。

Vue 3 项目中配置 Stylelint,核心目标是统一 CSS/SCSS/Vue 单文件组件中样式书写规范,防止低级错误(比如重复属性、无效单位)、保证属性排序一致、规避浏览器兼容性写法。它不负责格式化(那是 Prettier 的事),而是做“样式层面的 ESLint”。
安装与基础依赖
Stylelint 需要解析不同语法(CSS、SCSS、Vue 中的 style),所以得按需装解析器和插件:
- 主工具:
stylelint(必须) - 通用扩展:
stylelint-config-standard(提供主流 CSS 规则集) - Vue 支持:
stylelint-config-html或stylelint-config-recommended-vue(识别 .vue 文件中的 style 块) - SCSS 支持(如用 SCSS):
postcss-scss+stylelint-config-standard-scss - 排序规则(推荐):
stylelint-order+stylelint-config-property-sort-order-smacss(让 padding 写在 margin 后、color 写在 font-size 前等) - 与 Prettier 协同:
stylelint-prettier(把 Prettier 的样式格式规则也纳入 Stylelint 检查流)
执行安装(以 pnpm 为例):
pnpm add -D stylelint stylelint-config-standard stylelint-config-html stylelint-config-recommended-vue stylelint-order stylelint-config-property-sort-order-smacss stylelint-prettier postcss-html创建配置文件 stylelint.config.js
根目录新建 stylelint.config.js,内容示例如下(适配 Vue + CSS/SCSS):
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-config-html',
'stylelint-config-recommended-vue',
'stylelint-config-property-sort-order-smacss',
'stylelint-prettier'
],
plugins: ['stylelint-order', 'stylelint-prettier'],
rules: {
// 允许在 Vue 中使用 deep / global 等伪类
'selector-pseudo-class-no-unknown': [
true,
{ ignorePseudoClasses: ['deep', 'global'] }
],
// 允许 SCSS 中的 & 符号嵌套写法(若用 SCSS)
'scss/percent-placeholder-pattern': null,
// 关闭对 @tailwind 等工具类指令的报错
'at-rule-no-unknown': [
true,
{ ignoreAtRules: ['tailwind', 'apply', 'responsive'] }
]
},
overrides: [
{
files: ['**/*.scss', '**/*.sass'],
customSyntax: 'postcss-scss',
extends: ['stylelint-config-standard-scss', 'stylelint-config-recommended-vue/scss']
}
]
};
添加忽略文件 .stylelintignore
避免检查构建产物或第三方样式,新建 .stylelintignore:
dist/ node_modules/ public/ src/assets/styles/normalize.css
集成到开发与提交流程
让校验真正落地,不能只靠手动运行:
- 在
package.json加脚本:
"lint:style": "stylelint \"src/**/*.{css,scss,vue}\"" - 配合
lint-staged:只检查暂存区的样式文件,提升速度
例如 lint-staged 配置中加入:
"{src/**/*.{css,scss,vue}}": ["stylelint --fix"] - 搭配
husky:在 pre-commit 钩子中自动执行npm run lint:style,不通过则禁止提交
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











