ESLint 已支援 CSS 和基準

發布日期:2025 年 3 月 12 日,上次更新日期:2025 年 3 月 26 日

ESLint 一直是 JavaScript 的首選 Linter,提供各種設定和規則,協助開發人員在專案中強制執行良好的 JavaScript 樣式。ESLint 近期推出了支援在專案中檢查 CSS 的功能,提供額外規則來檢查樣式表的各個層面。

為了推出 CSS 支援功能,ESLint 現已提供 require-baseline 規則,可讓您在專案中 Lint CSS 時,指定要使用的基準值門檻。在本篇簡短文章中,您將瞭解如何使用這項規則,確保 CSS 符合「新基準」和「廣泛可用」門檻。

如何使用 ESLint 強制執行 CSS 基準功能

如果您之前曾使用 ESLint,在專案中加入 CSS 檢查的程序應該會相當快速。如要開始使用,請為專案安裝 @eslint/css 套件:

npm install @eslint/css --save-dev 

安裝完成後,您就可以將 @eslint/css 套件匯入現有的 ESLint 設定,為專案新增 CSS 檢查支援:

// eslint.config.js import css from "@eslint/css";  export default [   // Lint css files   {     files: ["src/css/**/*.css"],     plugins: {       css,     },     language: "css/css",     rules: {       "css/no-duplicate-imports": "error",       // Lint CSS files to ensure they are using       // only Baseline Widely available features:       "css/require-baseline": ["warn", {         available: "widely"       }]     },   }, ]; 

雖然 CSS 的 linting 本身就很實用,但 ESLint 提供的附加價值,是透過 linter 的 require-baseline 規則提供。在上述程式碼片段中,每當遇到未廣泛提供的 Baseline 功能,系統就會產生警告。這項資訊可透過規則的 available 屬性指定,該屬性也接受 "newly" 值,可確保使用的所有 CSS 功能至少為新基準可用。

設定完成後,您可以在專案根目錄中執行 ESLint,以便檢查專案的 CSS:

npx eslint 

完成後,ESLint 會提供任何有關專案 CSS 的警告,如下所示:

/var/www/my-cool-web-project/src/css/styles.css   269:3   warning  Property 'overflow' is not a widely available baseline feature                     css/require-baseline   427:3   warning  Property 'overflow' is not a widely available baseline feature                     css/require-baseline   444:12  warning  Value 'contents' of property 'display' is not a widely available baseline feature  css/require-baseline   500:3   warning  Property 'resize' is not a widely available baseline feature                       css/require-baseline   573:5   warning  Property 'overflow' is not a widely available baseline feature                     css/require-baseline 

ESLint 提供這項功能的一大優點,就是您可以在任何使用 ESLint 的工具工作流程中使用這項功能。舉例來說,如果您使用 webpack,可以使用 eslint-webpack-plugin,在專案建構期間吐出 Linter 輸出內容:

// Import the ESLint plugin: import ESLintPlugin from "eslint-webpack-plugin";  // Webpack config: export default {   // Prior config code omitted...   plugins: [     new ESLintPlugin({       // Add the `"css"` extension to ensure       // CSS files are linted as well:       extensions: ["js", "css"]     })   ] }; 

有了這些實用的 ESLint 新功能,您現在就能確保專案使用基準 CSS 功能,而無須額外付出額外努力。快來試試看!您可能會驚訝地發現,您的專案中使用了一些 Baseline 功能。如要進一步瞭解運作方式,請參閱 require-baseline 規則的說明文件