如何在JSX/TSX中使用// NOSONAR禁用代码检测问题?
在JSX/TSX中如何用NOSONAR禁用单行代码检测?
在TypeScript里,我可以用// NOSONAR来禁用特定行的SonarQube代码检测,示例如下:
var x = 1; // NOSONAR
但在JSX/TSX中该怎么实现同样的功能?我试了好几种写法都没成功,最近的尝试代码如下:
<Animated.ScrollView refreshControl={refreshControl} contentInsetAdjustmentBehavior="automatic"> {lastAuthEvents.map( ({ key, on, authState, type, reason }: LoggedAuthEvent, index) => ( <View key={`.${index}`} borderBottomColor="silver" borderBottomWidth={1} paddingTop={index === 0 ? 0 : 16} paddingBottom={16}>{/* // NOSONAR */} <View flexDirection="row"> <Text fontSize={16}>{format(on, "HH:mm:ss")}</Text> <Text fontSize={16}>{AuthState[authState]}</Text> <FontAwesome name="arrow-circle-right" color="#ffffff" /> <Text fontSize={16}>{type}</Text> </View> <Text>{reason}</Text> </View> ) )} </Animated.ScrollView>
我还试过这些写法:
{/* NOSONAR */} {// NOSONAR} // 这种写法会报错
正确实现方式
在JSX/TSX中使用NOSONAR禁用代码检测,要注意两个关键点:
- 不要在JSX注释里加多余的
//,直接写/* NOSONAR */即可。 - 必须让注释和需要忽略检测的代码处于同一行,SonarQube的行级禁用是基于行匹配的。
针对你的代码,正确写法如下:
<Animated.ScrollView refreshControl={refreshControl} contentInsetAdjustmentBehavior="automatic"> {lastAuthEvents.map( ({ key, on, authState, type, reason }: LoggedAuthEvent, index) => ( <View key={`.${index}`} borderBottomColor="silver" borderBottomWidth={1} paddingTop={index === 0 ? 0 : 16} paddingBottom={16} /* NOSONAR */> <View flexDirection="row"> <Text fontSize={16}>{format(on, "HH:mm:ss")}</Text> <Text fontSize={16}>{AuthState[authState]}</Text> <FontAwesome name="arrow-circle-right" color="#ffffff" /> <Text fontSize={16}>{type}</Text> </View> <Text>{reason}</Text> </View> ) )} </Animated.ScrollView>
如果要禁用整个map表达式的检测,也可以把注释放在表达式开头的同一行:
{lastAuthEvents.map(/* NOSONAR */ (item, index) => ( <View key={index}>{item.text}</View> ))}
避坑提示
- 绝对不能用
{// NOSONAR}这种写法,JSX里的{}是JavaScript表达式容器,单行注释//放在里面会直接触发语法错误。 - 确保
NOSONAR注释和目标代码在同一行,跨行的注释无法触发行级禁用规则。
内容的提问来源于stack exchange,提问作者Archimedes Trajano
相关产品推荐
相关产品推荐

