Stylelint / 幫助你整理 CSS 的好幫手
7 min readNov 30, 2022
因為設置了許多次 stylelint,但偶而會忘記怎麼成功、偶而會用不好又要再找資料,因此這邊再統一記錄一下
一、安裝套件
首先在專案中,要安裝三個套件
yarn add stylelint stylelint-config-standard stylelint-order -D
在我當下使用的版本各為
- stylelint:^14.15.0
- stylelint-config-standard:^29.0.0
- stylelint-order:^5.0.0
然後 VS Code 的 Extensions 需要額外安裝 Prettier — Code formatter 與 Stylelint
二、設定檔配置
接下來需要至 settings.json(有次我打成 setting.json,結果根本沒吃到設定檔)中設置 stylelint.validate,因為 default 只有 css、less 與 postcss,像我較常使用 scss 就需再添加 scss 至設定檔,且因為每個專案的 stylelint 都有不同,因此建議放到 project 的 setting.json 而非 global 的
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": true
},
"stylelint.validate": ["css", "less", "postcss", "scss"],
且需要新增 codeActionOnSave 中的 stylelint,這樣在存檔時,才會自動幫檔案 formatk
然後在 root 資料夾建立 .stylelintrc.json
{
"extends": "stylelint-config-standard",
"plugins": ["stylelint-order"],
"rules": {
// === stylelint-order 的配置 ===
"order/order": ["custom-properties", "dollar-variables", "declarations", "rules", "at-rules"],
"order/properties-order": [
"position",
"top",
"bottom",
"right",
"left",
"display",
"align-items",
"justify-content",
"float",
"clear",
"overflow",
"overflow-x",
"overflow-y",
"margin",
"margin-top",
"margin-right",
"margin-bogttom",
"margin-left",
"padding",
"padding-top",
"padding-right",
"padding-bottom",
"padding-left",
"width",
"min-width",
"max-width",
"height",
"min-height",
"max-height",
"font-size",
"font-family",
"font-weight",
"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",
"z-index",
"box-shadow",
"text-shadow",
"resize",
"transition"
],
// === Stylelint Config Generator 產出的設定規則 ===
"indentation": 2,
"string-quotes": "single",
"no-duplicate-selectors": true,
"selector-combinator-space-after": "always",
"declaration-colon-space-after": "always",
"number-leading-zero": "never",
"rule-empty-line-before": "always-multi-line",
"selector-pseudo-element-colon-notation": "double",
"media-feature-range-operator-space-before": "always",
"media-feature-range-operator-space-after": "always",
"media-feature-colon-space-after": "always"
}
}
- 在 extends 選用剛剛安裝的 stylelint-config-standard,市面上有很多不同的 extends,會對應到不同的 rules,後來比較習慣使用這款
- 可以使用 Stylelint Config Generator 來配置你喜歡的規則,例如:冒號前面前要不要空白、中括號中間要不要留白 …. 等規則
- 然後是 stylelint-order 套件,配置檔案都會以 order/… 開頭,像是order/order 是針對大種類來做順序編排,例如 @ media、 custom-properties …
- 而 order/properties-order 就是針對自定義的 properties 來做順序編排,關於 stylelint-order 更多的相關資訊可以看此連結