51

如何改善既有 JS 代码:修复常见的 ESLint 报警(四)

 5 years ago
source link: https://github.com/cssmagic/blog/issues/94?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言

ESLint 是目前最主流、最强大的 JS 代码校验工具。当我们的代码触发了 ESLint 的报警规则时,ESLint 就会提示错误。

本系列文章将详细讲解那些需要手工介入修复的 ESLint 规则,帮助你顺利地把既有代码迁移到 ESLint 的保护之中。

no-fallthrough

禁止在 switch / case 语句中使用穿透特性。

我们在 JS(以及大多数类 C 语言)里写 switch/case 往往会踩的一个坑就是 “穿透”。简单解释一下,在 swithc 的执行过程中,匹配了一个 case 并执行完这个 case 的代码之后,如果没有遇到 break 语句,则会继续执行 后续所有 case 的代码。

这是一个非常反直觉的设计,也是 bug 的温床。因此 ESLint 提供了 no-fallthrough 这条规则,避免无意中踩到穿透特性的坑。

但如果在某些场景下,你真的需要这个特性怎么办?ESLint 允许你通过注释来说明你是真的在利用穿透特性,只要注释符合特定格式就可以抑制报警:

switch (foobar) {
    case 1:
        doSomething()
        // fall through

    case 2:
        doSomethingElse()
}

no-undef

禁止使用未定义的变量。

当我们在使用一个变量之前忘了声明它,这条规则就会报警提醒我们。不过大多数触发报警的代码是在引用一个全局变量,而 ESLint 并未理解。

比如有以下代码:

// namespace
window.Auth = { /* ... */ }

// ...

// init
if (page && Auth[page]) {
    Auth[page]()
}

在后面这个 if 语句中有对 Auth 的引用。虽然我们在第一行已经定义了 Auth 这个全局变量( window.Auth = ... ),但 ESLint 无法识别,这条规则会报警。

有两种方式可以修复这个问题…………

……

……

完整文章在 “CSS魔法” 公众号首发,微信扫码立即阅读:

Mn6VZr3.png!web

© Creative Commons BY-NC-ND 4.0   | 我要订阅 |   我要打赏


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK