青训营大项目 | less项目配置stylelint

1,483 阅读2分钟

这是我参与「第五届青训营 」笔记创作活动的第14天

安装

yarn add stylelint stylelint-config-standard stylelint-config-rational-order stylelint-config-prettier postcss-less -d
  • stylelint — 运行工具
  • stylelint-config-standard — stylelint的推荐配置
  • stylelint-config-prettier —关闭所有不必要的或可能与Prettier冲突的规则
  • stylelint-config-rational-order — 通过按rational顺序组合在一起对相关属性声明进行排序
  • postcss-less — 用于解析less

配置

我们基于antdv4的源代码进行配置,样式函数大多为动画函数

{
    "extends": [
        "stylelint-config-standard",
        "stylelint-config-rational-order",
        "stylelint-config-prettier"
    ],
    "customSyntax": "postcss-less",
    "rules": {
        // 不允许使用位置函数,除ignoreFunctions数组下的元素
        "function-no-unknown": [ 
            true,
            {
              "ignoreFunctions": [
                "fade",
                "fadeout",
                "tint",
                "darken",
                "ceil",
                "fadein",
                "floor",
                "unit",
                "shade",
                "lighten",
                "percentage",
                "-",
                "~`colorPalette"
              ]
            }
        ],
          "import-notation": null, 
          "no-descending-specificity": null, // 允许低优先级的选择器出现在高优先级的选择器之后。
          "no-invalid-position-at-import-rule":null, // 允许在无效的地方使用import进行引入
          "declaration-empty-line-before":null, // 声明之前可以有空行
          "keyframes-name-pattern":null, // 关闭关键帧动画的命名形式,
          "custom-property-pattern":null, // 关闭定义属性的形式
          "number-max-precision":8, // 限制小数个数
          "alpha-value-notation":"number", // 设置alpha的方式为数字,较多用于不透明的值形式
          "color-function-notation":"legacy", // 设置颜色rgb等的写法,逗号相隔,a { color: rgba(12, 122, 231, 0.2) } 
          "property-no-vendor-prefix":null //允许属性的供应商前缀
    },
    
    // 忽略以下文件的检查
    "ignoreFiles": ["**/*.js", "**/*.jsx", "**/*.tsx", "**/*.ts", "**/*.json", "**/*.md"]
}

检查和修正

package.json文件scripts中添加命令

"style": "stylelint \"src/**/*.(less|css)\" --fix",

VSCode配置

  1. 安裝 StyleLint
  2. settings.json文件中进行设置
{ "editor.codeActionsOnSave": { "source.fixAll.stylelint": true } }

搭配lint-staged使用

lint-staged 就是基于此种场景开发的,其中 staged 是 Git 里面的概念,指待提交区,使用git commit -a,或者先 git add 然后 git commit 的时候,你的修改代码都会经过待提交区。

  "lint-staged": {
    "*.{less,css}":[
        "stylelint --fix"
    ]
  },

那么代码就会在暂存区对其进行检查和修改