安装依赖
yarn add stylelint stylelint-scss stylelint-config-standard stylelint-config-standard-scss postcss postcss-scss stylelint-order stylelint-config-rational-order stylelint-css-modules-no-global-scoped-selector @mtfe/eslint-plugin-jsx-style -D
修改package.json
"scripts": {
...,
// 新增 (由于加上了--fix,务必需要diff check一下,也可以去掉--fix)
"lint:style": "npx stylelint 'src/**/*.scss' --cache --fix",
// 增加 yarn lint:style,可以去掉commit-msg和commitlint
"husky:install": "yarn husky install && yarn husky set .husky/commit-msg 'yarn commitlint -e $HUSKY_GIT_PARAMS' && yarn husky set .husky/pre-commit 'yarn tsc --noEmit && yarn lint && yarn lint:style'"
},
重新安装husky
yarn husky:install
新增.stylelintrc.js配置文件
module.exports = {
extends: [
'stylelint-config-standard-scss',
'stylelint-config-rational-order'
],
overrides: [
{
files: ['**/*.scss'],
customSyntax: 'postcss-scss'
}
],
ignoreFiles: ['node_modules/**', 'build/**'],
"plugins": [
'stylelint-css-modules-no-global-scoped-selector'
],
rules: {
// 4个空格缩进
indentation: 4,
// 禁止使用!important
'declaration-no-important': true,
// 禁止使用id选择器
'selector-max-id': 0,
// css文件禁止使用//注释 (不包括.scss文件)
'no-invalid-double-slash-comments': true,
// 选择器命名(驼峰命名, .fur-, .mtd-除外)
'selector-class-pattern': [
'^(([a-z][a-z1-9]*([A-Z][a-z1-9]+)*)|(fur-.*)|(mtd.*))$',
{
message: (selector) => `Expected class selector "${selector}" to be camelCase`,
},
],
// :global
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['/^global/']
}
],
// 禁止使用颜色命名
'color-named': 'never',
// 嵌套层级
'max-nesting-depth': 5,
// 禁止全局作用域
"css-modules/no-global-scoped-selector": true,
},
// 可以先改为warning,修复后删掉或改为error
"defaultSeverity": 'error'
}
新增.stylelintignore文件
# dependencies
node_modules
# production
build
新增eslint插件
plugins: [
...
// 新增(scss导入命名约定)
'@mtfe/jsx-style'
],
rules: {
...
// 新增 (禁止行内样式),校验级别可以先改为'warn',修复后改为'error'
'@mtfe/jsx-style/no-inline-styles': 'error',
// 新增 (import变量名建议改为 styles),校验级别可以先改为'warn',修复后改为'error'
'@mtfe/jsx-style/import-styles': 'error',
}
global.scss文件忽略规则
// 全局作用域选择器
/* stylelint-disable css-modules/no-global-scoped-selector */
// id选择器
/* stylelint-disable selector-max-id */
vscode配置
- 安装Stylelint插件
- settings.json文件新增配置
"css.validate": false,
"less.validate": false,
"scss.validate": false,
"stylelint.validate": [
"css",
"postcss",
"scss"
],
// 保存自动修复, 或使用命令Fix all auto-fixable problems
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": true
},
如果项目中没有settings.json文件,参考如下操作步骤
创建settings.json文件
- Ctrl+Shift+P 快捷键
- 输入settings搜索
- 点击红框内容,会在项目的根目录自动创建.vscode/settings.json
规则讨论
| rule | bad | good | |
|---|---|---|---|
| font-family-no-missing-generic-family-keyword | font-family: PingFang SC | font-family: "PingFang SC", sans-serif | |
| color-function-notation | background: rgba(217, 217, 217, 0.27843) | background: rgba(217 217 217 27.843%) | |