Unexpected XML declaration. The XML declaration must be the first node in the document and no white

你遇到的 ESLint 错误: ``` ESLint: Unexpected lexical declaration in case block. (no-case-declarations) ``` 是因为你在 `switch` 语句的 `case` 分支中使用了 **`let`、`const` 或 `class`** 等 **词法声明(lexical declarations)**,而 ESLint 的 [`no-case-declarations`](https://eslint.org/docs/latest/rules/no-case-declarations) 规则禁止这样做。 --- ### ❌ 错误示例 ```javascript switch (value) { case 'A': let foo = 1; // ❌ 报错:Unexpected lexical declaration in case block const bar = 2; console.log(foo, bar); break; case 'B': class MyClass {} // ❌ 同样被禁止 break; } ``` 虽然这段代码在 JavaScript 中 **语法上是合法的**(因为 `case` 块中的 `let/const` 只要被大括号包裹就不会跨 case 泄漏),但由于作用域容易让人误解,ESLint 默认禁止这种写法。 --- ### ✅ 正确解决方法 #### ✅ 方法一:用大括号创建块级作用域(推荐) 将 `let`、`const` 声明包裹在 `{}` 块中,明确限定作用域: ```javascript switch (value) { case 'A': { let foo = 1; const bar = 2; console.log(foo, bar); break; } case 'B': { class MyClass {} const instance = new MyClass(); break; } default: break; } ``` ✅ 这样写既合法,又符合 ESLint 规范,而且清晰地表达了变量的作用域范围。 --- #### ✅ 方法二:提升声明到 `switch` 外部 如果你不需要块级隔离,可以将变量提到 `switch` 外: ```javascript let foo; let bar; switch (value) { case 'A': foo = 1; bar = 2; console.log(foo, bar); break; case 'B': foo = 3; bar = 4; break; default: foo = 0; bar = 0; } ``` ⚠️ 注意:这种方式适用于变量需要在多个 `case` 中共享的情况,但可读性和安全性不如块级作用域。 --- #### ✅ 方法三:关闭该规则(不推荐) 如果你确定团队能管理好这种风险,可以在 `.eslintrc.js` 中关闭此规则: ```js // .eslintrc.js module.exports = { rules: { 'no-case-declarations': 'off', }, }; ``` 或者在代码中临时禁用: ```js switch (value) { case 'A': // eslint-disable-next-line no-case-declarations const foo = 1; console.log(foo); break; } ``` 但建议优先使用 **方法一(加 `{}` 块)**,这是最安全和清晰的方式。 --- ### 🔍 为什么 ESLint 要禁止 case 中的声明? 考虑这个例子: ```js switch (value) { case 'A': let x = 1; // fall through case 'B': console.log(x); // 如果 value 是 'B',x 是 undefined!但语法不报错 } ``` 由于没有块级作用域,`x` 在 `'B'` 中仍然可见(但未初始化),这可能导致意外错误。使用 `{}` 显式划分作用域可以避免这类陷阱。 --- ### 总结 - ✅ 推荐做法:在 `case` 中使用 `{}` 包裹 `let/const/class` 声明。 - 🛑 避免直接在 `case` 下写 `let/const`。 - 🧩 原理:防止变量提升或作用域混淆带来的 bug。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值