Stylelint

Stylelint

StyleLint 是一套檢查 CSS Coding Style

  • 安裝 stylelint npm install stylelint -D
  • 安裝 CSS 配置 npm install stylelint-config-standard -D
  • 安裝 SCSS 配置 npm install stylelint-config-sass-guidelines stylelint-scss -D
  • 安裝其他配置 可以參考 Stylelint 官方Github
  • 建立 .stylelintrc.cjs

    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
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    module.exports = {
    // 繼承推薦規範配置
    extends: [
    "stylelint-config-standard",
    "stylelint-config-recommended-scss",
    "stylelint-config-recommended-vue/scss",
    "stylelint-config-html/vue",
    "stylelint-config-recess-order",
    ],
    // 指定不同文件對應的解析器
    overrides: [
    {
    files: ["**/*.{vue,html}"],
    customSyntax: "postcss-html",
    },
    {
    files: ["**/*.{css,scss}"],
    customSyntax: "postcss-scss",
    },
    ],
    // 自定義規則
    rules: {
    "import-notation": "string", // 指定導入CSS文件的方式("string"|"url")
    "selector-class-pattern": null, // 選擇器類名命名規則
    "custom-property-pattern": null, //自定義屬性命名規則
    "keyframes-name-pattern": null, // 動畫節點樣式命名規則
    "no-descending-specificity": null, // 允許無降序特異性
    // 允許 global 、export 、deep偽類
    "selector-pseudo-class-no-unknown": [
    true,
    {
    ignorePseudoClasses: ["global", "export", "deep"],
    },
    ],
    // 允許未知屬性
    "property-no-unknown": [
    true,
    {
    ignoreProperties: ["menuBg", "menuText", "menuActiveText"],
    },
    ],
    },
    };

    在 VS Code setting.json 加入自動修正錯誤,

    1
    2
    3
    4
    "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
    },

    VS Code 安裝 stylelint套件

    套用到專案

    1
    2
    3
    4
    // 檢查錯誤
    npx stylelint "**/*.css"
    // 修正錯誤
    npx stylelint "**/*.css" --fix

    或是在 package.json 內設定,透過 npm run lint:style 去執行

    1
    2
    3
    4
    5
    6
    7
    8
    / package.json

    {
    "scripts": {
    "check:style": "stylelint **/*.{css,scss,sass,vue}",
    "lint:style": "stylelint **/*.{css,scss,sass,vue} --fix"
    }
    }

    stylelint參考資料

    stylelint失效問題