StyleX + ESLint:当最佳实践相互冲突

发布: (2026年1月2日 GMT+8 06:51)
3 min read
原文: Dev.to

Source: Dev.to

设置:遵循所有规则

Vite 配置

使用 v0.15.0 推荐的 enableMediaQueryOrder: true

// vite.config.js
styleXUnplugin.vite({
  enableMediaQueryOrder: true,
})

ESLint 配置

使用推荐的 StyleX 插件规则:

// eslint.config.mjs
rules: {
  "@stylexjs/valid-styles": "error",
  "@stylexjs/sort-keys": "warn", // 保持样式有序!
}

响应式样式

使用内联字符串并遵循正确的层叠顺序:

const styles = stylex.create({
  container: {
    padding: {
      default: "2rem",
      "@media (max-width: 768px)": "1.5rem", // 平板
      "@media (max-width: 640px)": "1rem",   // 手机
    },
  },
});

顺序为先写较大的断点,这样较小的断点可以在 CSS 层叠中覆盖它们。

问题:ESLint 给出的友好警告

运行 npm run lint 时出现:

warning  StyleX property key "@media (max-width: 640px)"
         should be above "@media (max-width: 768px)"

运行 npm run lint -- --fix 让 ESLint “修复”了代码:

padding: {
  default: "2rem",
  "@media (max-width: 640px)": "1rem", // 现在排在前面 (640)
}

“现在你可以按自己想要的顺序编写重叠的媒体查询,编译器会重新写它们,使后面的查询优先于前面的查询。”
StyleX v0.15.0 发布说明

该特性依赖 源代码顺序,但 StyleX ESLint 插件的 sort-keys 规则会破坏这种顺序。两者产生冲突。

变通办法

在上游问题修复之前,可在响应式属性外层使用 ESLint 禁用块:

const styles = stylex.create({
  container: {
    /* eslint-disable @stylexjs/sort-keys -- max-width cascade: larger breakpoints first */
    padding: {
      default: "2rem",
      "@media (max-width: 768px)": "1.5rem",
      "@media (max-width: 640px)": "1rem",
    },
    /* eslint-enable @stylexjs/sort-keys */
  },
});

块注释阻止 sort-keys 规则对嵌套的媒体查询进行重新排序,同时仍然让该规则在其他地方生效。

关键要点

  • 不要盲目相信 --fix —— 自动修复可能会破坏 linters 无法理解的语义顺序。
  • 在 lint 之后测试响应式样式 —— 确认断点在运行 eslint --fix 后仍然有效。
  • 记录例外情况 —— 类似 -- max-width cascade: larger breakpoints first 的注释可以解释为何禁用规则。
  • 在上游提交问题 —— 报告此问题有助于维护者改进规则。

我们需要的修复

@stylexjs/sort-keys 规则应当:

  1. 在媒体查询对象内部跳过排序 —— 检测 @media 键并保留作者的顺序。
  2. 按特异性排序 —— 理解 max-width 查询需要降序,而 min-width 查询需要升序。
  3. 提供配置选项 —— 允许用户为特定模式关闭排序。

在这些改进落地之前,请保持使用 ESLint 禁用注释。

参考资料:

Back to Blog

相关文章

阅读更多 »

入门 eslint-plugin-secure-coding

封面图片:Getting Started with eslint-plugin-secure-coding https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/ht...

入门 eslint-plugin-pg

快速安装 bash npm install --save-dev eslint-plugin-pg Flat Config js // eslint.config.js import pg from 'eslint-plugin-pg'; export default pg.configs.reco...