前端規范之CSS規范(Stylelint)


    代碼規范是軟件開發領域經久不衰的話題,幾乎所有工程師在開發過程中都會遇到或思考過這一問題。而隨着前端應用的大型化和復雜化,越來越多的前端團隊也開始重視代碼規范。同樣,前段時間,筆者所在的團隊也開展了一波開源治理,而其中代碼規范就占據了很重要的一項。接下來的幾篇文章,將會對JS代碼規范、CSS規范、Git提交規范以及Git工作流規范進行詳細的介紹~

    系列文章:

    本文主要介紹了前端規范之CSS規范(Stylelint),將會對Stylelint的使用進行介紹,歡迎大家交流討論~

 

1. Stylelint介紹及安裝

1.1 什么是Stylelint

    Stylelint是一個強大的,現代的代碼檢查工具,與ESLint類似,Stylelint能夠通過定義一系列的編碼風格規則幫助我們避免在樣式表中出現錯誤。

    目前在開源社區上,關於CSS Lint的解決方案主要包括了csslint、SCSS-Lint和Stylelint等幾種。而由於Stylelint在技術架構上基於AST 的方式擴展CSS,除原生CSS 語法,其也支持 SCSS、Less 這類預處理器,並且也有非常多的第三方插件,因此我們團隊選擇了Stylelint作為CSS Lint工具。

    官方文檔:https://stylelint.io/

1.2 安裝Stylelint

   可以選采用npm安裝Stylelint。其中,stylelint-config-standard是Stylelint的標准配置。如果想使用airbnb或prettier的規范,也可以將stylelint-config-standard改為stylelint-config-airbnb或stylelint-config-prettier。

npm install stylelint stylelint-config-standard --save-dev

1.3 安裝適配預處理語法的插件

    如果我們項目中采用了如sass或less等css預處理器,那么可以安裝適配預處理語法的插件。以sass為例,需要安裝stylelint-scss插件。

npm install stylelint-scss --save-dev

1.4 安裝CSS屬性排序插件

    我們也可以選擇安裝stylelint-order插件。該插件能夠強制我們按照某個順序編寫css,比如先寫定位,再寫盒模型,再寫內容區樣式,最后寫CSS3相關屬性,這樣可以更好的保證我們代碼的可讀性。

npm install stylelint-order --save-dev

 

2. Stylelint配置

2.1 Stylelint配置方式

    安裝好Stylelint之后,就需要對Stylelint進行配置。Stylelint的配置方式包括了以下幾種:

  • 在package.json中添加stylelint屬性並添加規則
  • 在.stylelintrc文件中指定,.stylelintrc文件支持添加一個文件擴展名來區分 JSON,YAML 或 JS 格式,如創建.stylelintrc.json、.stylelintrc.yaml、.stylelintrc.yml或.stylelintrc.js文件
  • 在stylelint.config.js文件中指定,該文件將會exports一個配置對象

    在這里,我們選擇了在項目根目錄創建.stylelintrc.js來配置Stylelint。

    

    在.stylelintrc.js文件中,我們可以指定要配置的內容,下面給出了一個配置文件的例子。

    其中,該配置文件采用了stylelint-config-standard標准配置,並且添加了stylelint-order插件用於CSS屬性排序,在rules中,可以指定聲明塊內屬性的順序,也可以自定義CSS檢查規則。比如定義了color-hex-case為lower,表示CSS文件的顏色值都必須小寫,否則會報錯。

module.exports = {
  plugins: ['stylelint-order'],

  extends: ['stylelint-config-standard'],

  rules: {
    // 指定聲明塊內屬性的字母順序
    'order/properties-order': [
      'position',
      'top',
      'right',
      'bottom',
      'left',
      'z-index',
      'display',
      'float',
      'width',
      'height',
      'max-width',
      'max-height',
      'min-width',
      'min-height',
      'padding',
      'padding-top',
      'padding-right',
      'padding-bottom',
      'padding-left',
      'margin',
      'margin-top',
      'margin-right',
      'margin-bottom',
      'margin-left',
      'margin-collapse',
      'margin-top-collapse',
      'margin-right-collapse',
      'margin-bottom-collapse',
      'margin-left-collapse',
      'overflow',
      'overflow-x',
      'overflow-y',
      'clip',
      'clear',
      'font',
      'font-family',
      'font-size',
      'font-smoothing',
      'osx-font-smoothing',
      'font-style',
      'font-weight',
      'hyphens',
      'src',
      'line-height',
      'letter-spacing',
      'word-spacing',
      'color',
      'text-align',
      'text-decoration',
      'text-indent',
      'text-overflow',
      'text-rendering',
      'text-size-adjust',
      'text-shadow',
      'text-transform',
      'word-break',
      'word-wrap',
      'white-space',
      'vertical-align',
      'list-style',
      'list-style-type',
      'list-style-position',
      'list-style-image',
      'pointer-events',
      'cursor',
      'background',
      'background-attachment',
      'background-color',
      'background-image',
      'background-position',
      'background-repeat',
      'background-size',
      'border',
      'border-collapse',
      'border-top',
      'border-right',
      'border-bottom',
      'border-left',
      'border-color',
      'border-image',
      'border-top-color',
      'border-right-color',
      'border-bottom-color',
      'border-left-color',
      'border-spacing',
      'border-style',
      'border-top-style',
      'border-right-style',
      'border-bottom-style',
      'border-left-style',
      'border-width',
      'border-top-width',
      'border-right-width',
      'border-bottom-width',
      'border-left-width',
      'border-radius',
      'border-top-right-radius',
      'border-bottom-right-radius',
      'border-bottom-left-radius',
      'border-top-left-radius',
      'border-radius-topright',
      'border-radius-bottomright',
      'border-radius-bottomleft',
      'border-radius-topleft',
      'content',
      'quotes',
      'outline',
      'outline-offset',
      'opacity',
      'filter',
      'visibility',
      'size',
      'zoom',
      'transform',
      'box-align',
      'box-flex',
      'box-orient',
      'box-pack',
      'box-shadow',
      'box-sizing',
      'table-layout',
      'animation',
      'animation-delay',
      'animation-duration',
      'animation-iteration-count',
      'animation-name',
      'animation-play-state',
      'animation-timing-function',
      'animation-fill-mode',
      'transition',
      'transition-delay',
      'transition-duration',
      'transition-property',
      'transition-timing-function',
      'background-clip',
      'backface-visibility',
      'resize',
      'appearance',
      'user-select',
      'interpolation-mode',
      'direction',
      'marks',
      'page',
      'set-link-source',
      'unicode-bidi',
      'speak',
    ],

// 顏色值要小寫
'color-hex-case': 'lower',
'number-leading-zero': 'always', }, };

2.2 Stylelint配置項

    在上面的配置文件中,我們主要定義了一個配置對象,接下來將對常用的配置項進行介紹。

  (1)plugins

    plugins定義了一個數組,該配置項允許我們使用第三方插件,在該數組中,需要包含“定位器”標識出你要使用的插件,一個“定位器”可以是一個 npm 模塊名,一個絕對路徑,或一個相對於要調用的配置文件的路徑。

    一旦聲明了插件,在rules中需要為插件的規則添加選項,就像其他標准的規則一樣。你需要查看插件的文檔去了解規則的名稱。

{
  "plugins": [
“stylelint-order",
"../special-rule.js" ], "rules": {
"order/properties-order": [],
"plugin/special-rule": "everything" } }

  (2)extends

    extends定義了一個數組,該配置項允許我們extend一個已存在的配置文件(無論是你自己的還是第三方的配置)。當一個配置繼承了里一個配置,它將會添加自己的屬性並覆蓋原有的屬性。比如下面的代碼,我們就extend了Stylelint的標准配置。

{
  "extends": "stylelint-config-standard",
  "rules": {
    "indentation": "tab",
    "number-leading-zero": null
  }
}

    如果extends中包含多個配置項,那么數組中的每一項都優先於前一項,也就是說第二項會覆蓋第一項,第三項會覆蓋第一項和第二項,最后一項將覆蓋其它所有項。

{
  "extends": [
    "stylelint-config-standard",
    "./myExtendableConfig"
  ],
  "rules": {
    "indentation": "tab"
  }
}

  (3)rules

    rules定義了一個對象,屬性名為規則名稱,屬性值為規則取值,它告訴Stylelint該檢查什么,該怎么報錯,所有的規則都是默認關閉的。我們可以通過該選項開啟相應規則,進行相應的檢測。所有規則必須顯式的進行配置,因為沒有默認值。

    規則名稱主要由兩個部分組成,第一部分描述該規則應用於什么東西,第二部分表示該規則檢查了什么。

"number-leading-zero"
// ↑          ↑
// the thing  what the rule is checking

    當規則名稱應用於整個樣式表時只包含第二個部分:   

"no-eol-whitespace"
"indentation"
//
// what the rules are checking

    當規則名稱不同時,規則取值也不同。我們可以將某個規則設置為null禁用該規則。

{
  "rules": {
    "at-rule-blacklist": string|[],
    "at-rule-empty-line-before": "always"|"never",
    "at-rule-name-case": "lower"|"upper",
    "block-no-empty": null,
    ...
  }
}

    除了規則本身的取值之外,Stylelint還支持一些自定義配置,允許給規則傳遞一個數組,數組第一項是規則取值,第二項是自定義配置。

"selector-pseudo-class-no-unknown": [true, {
  "ignorePseudoClasses": ["global"]
}]

    通過自定義配置,我們可以指定: 

  • severity:錯誤級別,取值為”warning"或"error",默認情況下,所有規則的錯誤級別都為"error",通過defatuleServerity,可以修改錯誤級別的默認值
// error-level severity examples
{ "indentation": 2 }
{ "indentation": [2] }

// warning-level severity examples
{ "indentation": [2, { "severity": "warning" } ] }
{ "indentation": [2, {
    "except": ["value"],
    "severity": "warning"
  }]
}
  • message:當一個規則被觸發時,如果你想實現一個自定義的消息,可以給規則的傳遞"message“作為第二選項,如果提供,將替代提供的任何標准的消息。例如,以下規則配置會使用一些自定義的消息:
  "color-hex-case": [ "lower", {
    "message": "Lowercase letters are easier to distinguish from numbers"
  } ],
  "indentation": [ 2, {
    "ignore": ["block"],
    "message": "Please use 2 spaces for indentation. Tabs make The Architect grumpy.",
    "severity": "warning"
  } ]
}

  (4)processors

    Processors是Stylelint的鈎子函數,只能用在命令行和Node API,不適用於PostCSS插件。Processors可以使Stylelint檢測非樣式表文件中的CSS。例如,可以檢測HTML內中<style>標簽中的CSS,Markdown文件中代碼塊或JavaScript中的字符串。

    使用Processors的話,需要在配置中添加一個”processors“數組,包含“定位器”標識出你要使用的 processors。同上面的extends,一個“定位器”可以是一個 npm 模塊名,一個絕對路徑,或一個相對於要調用的配置文件的路徑。

{
  "processors": ["stylelint-html-processor"],
  "rules": {..}
}

    如果你的processor有選項,把它們放到一個數組里,第一項是“定位器”,第二項是選項對象。

{
  "processors": [
    "stylelint-html-processor",
    [ "some-other-processor", { "optionOne": true, "optionTwo": false } ]
  ],
  "rules": {..}
}

2.3 忽略特定文件的檢查

    在實際的使用場景中,我們可能存在某些文件或某行代碼,希望能夠跳過Stylelint的檢查或禁用某些規則,下面主要介紹了幾種跳過Stylelint檢查的方式:

  (1)使用注釋禁用規則

    使用/* stylelint-disable */,可以在代碼片段禁用所有規則或禁用特定規則。

/* stylelint-disable */
a {}
/* stylelint-enable */

/* stylelint-disable selector-no-id, declaration-no-important  */
#id {
  color: pink !important;
}
/* stylelint-enable */

    使用/* stylelint-disable-line */,可以在個別行上禁用規則。

#id { /* stylelint-disable-line */
  color: pink !important; /* stylelint-disable-line declaration-no-important */
}

    使用/* stylelint-disable-next-line */,可以在下一行禁用規則。

#id {
  /* stylelint-disable-next-line declaration-no-important */
  color: pink !important;
}

  (2)創建.stylelintignore忽略某些文件的檢查

    在項目根目錄創建.stylelintignore文件。

    

    在.stylelintignore中寫入需要跳過Stylelint檢查的文件名稱,比如下面的代碼將會忽略dist,node_modules和package.json文件的Stylelint檢查。

dist
node_modules
package.json

2.4 執行Stylelint檢查

    安裝配置好Stylelint之后,我們就可以運行Stylelint命令,對指定的文件進行CSS語法檢查,其中,--fix表示自動修復Stylelint錯誤。

    運行Stylelint命令后,如果什么也沒有輸出,就說明我們的文件已經通過Stylelint的檢查。如果輸出報錯信息,就說明沒有通過Stylelint的檢查,需要根據錯誤信息對代碼進行修復。

// 對某個文件進行檢查
stylelint "src/App.vue" --fix

// 對指定后綴名的文件進行檢查
stylelint "src/*.{html,vue,css,saas,scss,less}" --fix

    除了直接在命令行運行Stylelint命令方式之外,我們也可以在package.json中自定義Stylelint的啟動命令。如下面代碼所示,配置好package.json之后,我們通過運行npm run lint:css就能夠對指定文件進行Stylelint檢查。

{
"scripts": {
    "serve": "cross-env NODE_ENV=development vue-cli-service serve --mode dev",
    "serve:test": "cross-env NODE_ENV=test vue-cli-service serve --mode test",
    "serve:prod": "cross-env NODE_ENV=production vue-cli-service serve --mode prod",
    "build:dev": "cross-env NODE_ENV=production vue-cli-service build --mode dev",
    "build:test": "cross-env NODE_ENV=production vue-cli-service build --mode test",
    "build:prod": "cross-env NODE_ENV=production vue-cli-service build --mode prod",
    "lint": "vue-cli-service lint",
    "lint:css": "stylelint **/*.{vue,htm,html,css,sss,less,scss,sass} --fix"
  },
}

 

3. VSCode插件

3.1 安裝Stylelint插件

    為了讓我們在編寫代碼的過程中,能夠實時提示Stylelint錯誤,並且在保存文件時,能夠自動對當前文件進行Stylelint檢查和修復,我們可以在VSCode中安裝Stylelint插件。

    在VSCode的EXTENSIONS中找到Stylelint插件,點擊install就可以安裝Stylelint插件。

    

3.2 配置settings.json文件

    安裝好Stylelint插件之后,我們還需要配置VSCode的settings.json文件,讓我們的代碼在保存時,就能夠按照規范對CSS樣式進行檢查及自動fix。VSCode的settings.json設置分為工作區和用戶區兩個級別。其中,用戶區的設置會對所有項目生效,工作區的設置只能對當前項目生效。

  (1)用戶區settings.json配置

    點擊VSCode左下角的設置按鈕,選擇Settings,並且選擇以文本編輯的方式打開settings.json,在settings.json中加入以下代碼。

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {"source.fixAll.stylelint": true // 保存時是否自動 stylelint 修復
  },
}

  (2)工作區settings.json配置

    在項目根目錄創建.vscode目錄,並且在該目錄下創建settings.json文件。

    

    在settings.json中加入以下代碼。

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.stylelint": true // 保存時是否自動 stylelint 修復
  }
}

    配置好用戶區或工作區的settings.json后,當我們修改了某個文件的CSS代碼,並且保存時,就會發現能夠對當前文件自動進行stylelint檢查和修復了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM