如何为switch语句中有意穿透的case安全修复ESLint no-fallthrough错误?
解决ESLint no-fallthrough报错的三种实用方法
方法1:用ESLint认可的穿透标记注释
ESLint的no-fallthrough规则默认认可// falls through或/* falls through */这两种注释,用来标记这是有意的case穿透。你只需要把这个注释放在穿透case的最后,哪怕中间有功能注释,也要在功能注释后面补上它:
switch(num) { case 1: /* I also have comments in my code that explain functionality to non-developers. */ // falls through case 2: return "if one or two"; case 3: return "if three only"; }
方法2:临时关闭该代码块的规则
要是不想加特定注释,直接用ESLint的块级禁用语法,只在当前switch范围内关掉no-fallthrough规则就行:
/* eslint-disable no-fallthrough */ switch(num) { case 1: /* I also have comments in my code that explain functionality to non-developers. */ case 2: return "if one or two"; case 3: return "if three only"; } /* eslint-enable no-fallthrough */
方法3:自定义ESLint的穿透注释规则
如果想让现有功能注释也能被ESLint识别为穿透标记,可以在ESLint配置文件(比如.eslintrc.js)里修改no-fallthrough规则,添加自定义的注释匹配关键词:
module.exports = { // 其他配置项... rules: { "no-fallthrough": ["error", { "commentPattern": "falls through|intentional fallthrough|针对非开发者的功能说明" }] } };
只要你的注释里包含配置的关键词,ESLint就会判定这是有意穿透,不再报错。
内容的提问来源于stack exchange,提问作者Fuso
相关产品推荐
相关产品推荐

