default

styleLint

styleLint用于对样式(style)部分做规范检查和自动修复

使用stylelint需要注意版本,这里是stylelint@16,node@18,vscode@1.88.1

npm安装

cmd
pnpm instanll stylelint -D

安装完stylelint之后,我们还需要配置规则,一般来说,我们会用stylelint-config-standard这个库来作为标准的CSS规则库,它内置了许多CSS规则,如果还需要支持scss,则需要额外安装一个库stylelint-config-standard-scss

less需要自己额外再找一下

cmd
pnpm instanll stylelint-config-standard stylelint-config-standard-scss -D

另外我们再安装一个样式属性顺序规则

cmd
pnpm instanll stylelint-order -D 

给出一份简易的配置规则表

文件可以直接写成.stylelintrc也可以.stylelintrc.json,还可以.stylelintrc.js。这个没有强制要求

js
module.exports = {
	extends: ['stylelint-config-standard', 'stylelint-config-standard-scss'],
	plugins: ['stylelint-order'],
	ignoreFiles: ['**/*.js', '**/*.jsx', '**/*.tsx', '**/*.ts', '**/*.json', '**/*.md', '**/*.yaml'],
	rules: {
		'no-descending-specificity': null,
		// 指定样式的排序
		'order/properties-order': [
			'position',
			'top',
			'right',
			'bottom',
			'left',
			'z-index',
			'display',
			'justify-content',
			'align-items',
			'float',
			'clear',
			'overflow',
			'overflow-x',
			'overflow-y',
			'padding',
			'padding-top',
			'padding-right',
			'padding-bottom',
			'padding-left',
			'margin',
			'margin-top',
			'margin-right',
			'margin-bottom',
			'margin-left',
			'width',
			'min-width',
			'max-width',
			'height',
			'min-height',
			'max-height',
			'font-size',
			'font-family',
			'text-align',
			'text-justify',
			'text-indent',
			'text-overflow',
			'text-decoration',
			'white-space',
			'color',
			'background',
			'background-position',
			'background-repeat',
			'background-size',
			'background-color',
			'background-clip',
			'border',
			'border-style',
			'border-width',
			'border-color',
			'border-top-style',
			'border-top-width',
			'border-top-color',
			'border-right-style',
			'border-right-width',
			'border-right-color',
			'border-bottom-style',
			'border-bottom-width',
			'border-bottom-color',
			'border-left-style',
			'border-left-width',
			'border-left-color',
			'border-radius',
			'opacity',
			'filter',
			'list-style',
			'outline',
			'visibility',
			'box-shadow',
			'text-shadow',
			'resize',
			'transition',
		],
	},
};
 

新版本stylelint移除了与prettier冲突的规格(Migrating to 15.0.0 | Stylelint),把代码风格交给了prettier,也就是我们不用再去配置额外的prettier与stylelint兼容的插件库了

通过--fix命令手动修复我们的样式文件

cmd
stylelint --fix "*.{css,scss,less}"

配置vscode插件

基础使用

插件商店搜stylelint

image-20240422220224397

它与eslint有点类似,也需要安装stylelint包才能够起作用

cmd
pnpm instanll stylelint -D

然后还需要我们配置规则,例如上面的规则。配置好后,就可以在我们的编辑器中看到效果了

image-20240422231001342

自动修复

自动修复可以让我们在保存代码时,尽可能的帮助我们修复违反配置规则的代码,需要在setting中设置codeActionsOnSave,对于设置编辑器自动保存为afterDelay的人来说,你需要手动执行保存一下(Ctrl + S)才会执行修复。

json
"editor.formatOnSave": true,//这个开启,可以在保存的时候自动格式化
"editor.codeActionsOnSave": {//这个是在保存时,做的一些额外的操作
 "source.fixAll.stylelint": "explicit"
},
"stylelint.validate": [//检测的文件类型
        "css",
        "less",
        "scss",
        "sass"
    ],