利用 caniuse 结合 browserslist 对 JS 做兼容性检测

背景

前端开发的时候,我们经常会查 caniuse 看看某个方法是否兼容性足够,一旦不小心忘记查,则有可能使用了目标浏览器不支持的方法导致功能不可用甚至低端机上白屏,长期以往会降低质量同学对自己的信任分,比如 array.at 需要 Chrome >= 92 方可使用,而我们的目标浏览器是 90+。兼容性问题比较耗时间复现,有没有彻底的解决之道?

有,我们可以利用 eslint。

第一次尝试 eslint-plugin-compat ❌

www.npmjs.com/package/esl... 第一眼看上去蛮不错的,周下载量挺高 62w,而且支持 browserslist。按照配置尝试下。

js 复制代码
{
  "plugins": ["compat"],
  "extends": ["plugin:compat/recommended"],
  "env": {
    "browser": true,
  },
  // ...
}

package.json:

json 复制代码
"browserslist": [
    "Chrome >= 52",
    "Firefox >= 100",
    ">0.5%",
    "not dead"
  ],

但是发现代码并未检测到预期报错:

ts 复制代码
const array = result.cost.toString().split('.');
const last = array.at(-1); // 不能检测此处误用

翻阅资料 issue#539 发现,并不是我们配置有误,而是该包能力有限,无法推导变量类型故并不能检测原型链方法(若仅根据名字检测,则有误伤,因为任何对象都可以定义一个叫做 at 的方法),仅能检测静态方法。可以验证下:

ts 复制代码
const b = [4, 5, 6].at(2); // 能检测到 error
const foo = Object.values({});  // 能检测到 error

该 issue 同时给出了一个包 github.com/koddsson/es... 但是美中不足是这个包每周下载量仅有 6

第二次尝试 eslint-plugin-typescript-compat ✔️

这次我们使用 Trae 的 chat 模式问问最新的 DeepSeek-V3-0324:

我需要有一个根据 browserslist 规则检测 ts 函数兼容的 eslint 插件,比如我设置browserslist 为 ["Chrome > 90"] 则,即需要能检测到原型链上的方法而不仅仅是 static 方法

ts 复制代码
 const b = [4, 5, 6].at(2); //  需要被 eslint 检测到 error

 const array = result.cost.toString().split('.');
 const last = array.at(-1); // 也需要 error

🤖:根据你的需求,目前有一个 ESLint 插件可以基于 browserslist 规则检测 TypeScript 代码中的浏览器兼容性问题,包括原型链上的方法和静态方法。这个插件是 eslint-plugin-typescript-compat

下载量最高 8K 多,还行,按照官方文档配置下试试:

ts 复制代码
const array = result.cost.toString().split('.');
const last = array.at(-1); // 能检测到
const b = [4, 5, 6].at(2); // 能检测到
const foo = Object.values({}); // Chrome 54 即可支持,故此处不报错符合预期
console.log('last:', last, b, foo);

既能检测静态方法也能检测原型链方法,完美!

下一篇将介绍如何利用 caniuse 结合 browserslist 对 CSS 做兼容性检测。

相关推荐
油炸自行车7 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
OpenTiny社区12 小时前
操作ArkTS页面跳转及路由相关心得
前端·typescript·web·opentiny
柠檬の夏季12 小时前
TypeScript入门
typescript
万物皆对象66612 小时前
切换路由时页面空白问题(vue3)
前端·vue.js·typescript
突然好热12 小时前
TS 调试技巧
前端·javascript·typescript
晓杰'20 小时前
从0到1实现Balatro游戏后端(5):得分计算与单局结算流程实现
后端·typescript·node.js·游戏开发·项目实战·nestjs·webscoket
追光者♂21 小时前
【测评系列3】CSDN AI数字营销实测体验官:测试 开源项目——Superpowers 游戏引擎从零开发实战指南
人工智能·深度学习·机器学习·typescript·开源·游戏引擎·superpowers
ct97821 小时前
TypeScript 中的泛型
前端·javascript·typescript
烛衔溟1 天前
TypeScript 类的类型 —— 作为类型使用
javascript·ubuntu·typescript
豆包MarsCode1 天前
看了很多文章依旧不会写 Skill ? 保姆级攻略请查收!
trae