Stylelint CSS 格式化
Stylelint 是一个强大、先进的 CSS 代码检查器(linter),可以帮助你规避 CSS 代码中的错误并保持一致的编码风格。
- 安装依赖
stylelint- Stylelint 本体stylelint-config-prettier- 关闭 Stylelint 中与 Prettier 中会发生冲突的规则。stylelint-config-rational-order- 对 CSS 声明进行排序stylelint-config-standard- Stylelint 官方推荐规则stylelint-order使用stylelint-config-rational-order时依赖的模块
bash
pnpm add stylelint stylelint-config-prettier stylelint-config-rational-order stylelint-config-standard stylelint-order -D1
- 添加 StyleLint 配置文件
在根目录添加一个 .stylelintrc.js 文件,内容如下:
javascript
module.exports = {
root: true,
extends: [
'stylelint-config-standard',
'stylelint-config-rational-order',
'stylelint-config-prettier'
],
defaultSeverity: 'warning',
plugins: ['stylelint-order'],
rules: {
'no-empty-source': null,
'selector-class-pattern': null
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
在根目录添加一个 .stylelintignore 文件,内容如下:
plain
public
dist1
2
2
- 启用 Vue 文件支持
stylelint v14 版本默认是不支持 vue 文件中的 style 代码自动检测,详情我们可以查看官方迁移指南,具体配置如下:
stylelint-config-html解析 vue 文件postcss-html使用stylelint-config-html依赖的模块postcss-less对 less 文件进行解析
bash
pnpm add stylelint-config-html postcss-html postcss-less -D1
- 修改
.stylelintrc.js文件:
javascript
module.exports = {
root: true,
extends: [
'stylelint-config-standard',
'stylelint-config-rational-order',
'stylelint-config-prettier',
'stylelint-config-html/vue' // 需要放在最后一位
],
defaultSeverity: 'warning',
plugins: ['stylelint-order'],
rules: {
'no-empty-source': null,
'selector-class-pattern': null
},
overrides: [
{
files: ['*.vue', '**/*.vue'],
rules: {
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['deep', 'global']
}
],
'selector-pseudo-element-no-unknown': [
true,
{
ignorePseudoElements: ['v-deep', 'v-global', 'v-slotted']
}
]
}
}
]
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
- 在 VSCode 工作区配置中,添加如下代码:
json
{
"stylelint.validate": ["vue"] // Add "vue" language.
}1
2
3
2
3