ESLint 已支持 CSS 和基准

发布时间:2025 年 3 月 12 日;上次更新时间:2025 年 3 月 26 日

ESLint 长期以来一直是 JavaScript 的首选代码检查器,它提供各种设置和规则,可帮助开发者在项目中强制执行良好的 JavaScript 样式。最近,ESLint 推出了对项目中的 CSS 进行 lint 检查的支持,并提供了用于检查样式表各个方面的其他规则。

在推出 CSS 支持功能后,ESLint 现在提供 require-baseline 规则,让您可以在对项目中的 CSS 进行 lint 检查时指定要使用的 Baseline 阈值。在这篇简短的博文中,您将了解如何使用此规则来确保 CSS 达到“新近广泛可用”的基准阈值。

如何使用 ESLint 强制执行 Baseline CSS 功能

如果您之前使用过 ESLint,那么向项目添加 CSS lint 检查的过程应该会相当快。首先,为您的项目安装 @eslint/css 软件包:

npm install @eslint/css --save-dev

安装后,只需将 @eslint/css 包导入到现有的 ESLint 配置中,就可以让项目支持对 CSS 进行 lint 检查:

// 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 Widely available 的功能时,系统都会生成警告。这是通过规则的 available 属性指定的,该属性还接受 "newly" 值,以确保所使用的所有 CSS 功能至少处于“Baseline 新近可用”阶段。

设置好配置后,您可以在项目根目录下运行 ESLint,如下所示,以对项目的 CSS 进行 lint 检查:

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 让其在项目 build 期间输出 lint 结果:

// 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 的这些实用新功能,您现在可以确保项目使用 Baseline CSS 功能,而无需付出太多额外精力。快来试试吧!您可能会惊讶地发现,您的项目中使用了某些 Baseline 功能。如需详细了解此规则的运作方式,请参阅 require-baseline 规则的相关文档