Preventing code degradation with eslint-plugin-sonarjs

Tiso Alvarez Puccinelli
 / 
 2 min read

If you have worked with any sizable JavaScript project, be a front-end React application or a back-end Node service, you are most likely aware of the importance of using ESLint and other static code analysis tools.

In this article I'll show you a less know ESLint plugin that will help keep your codebase clean, by detecting early bugs and code smells. It's the eslint-plugin-sonarjs , made by the same guys behind SonarQube .

Installation

You'll need a JavaScript/Typescript project with ESLint configured  in it.

On your project, install eslint-plugin-sonarjs as a dev dependency using npm:

npm install eslint-plugin-sonarjs --save-dev

Once installed, update your .eslintrc file to include the following:

{
	"plugins": ["sonarjs"],
	"extends": ["plugin:sonarjs/recommended"]
}

What is it checking?

You can check the full list of rules here . By using the plugin:sonarjs/recommended configuration you'll have all of them enabled, with a few exceptions.

All those rules are intended to catch code that have potential bugs or code smells, like having too many switch case statements  or duplicated branches of code .

But the most important rule of this set is the Cognitive Complexity  one.

The Cognitive Complexity Rule

It checks against actual perceived complexity in code, given it a score on how hard is for a human to understand it. It's not the same as Cyclomatic Complexity , which measures how many different paths a programs code can take. You can read the full paper on Cognitive Complexity  to learn more about it.

This rule alone can act as a guard rail to prevent a project from becoming increasingly more complex and hard to maintain over time. You can also mix in a max-lines  rule to be even safer.

And since it's a ESLint rule with a configurable score, it helps reduce discussions about code quality and maintainability inside a pull request, making them more focused around the problem the PR is trying to solve.

Back to home page
Source code on Github 

Copyright © 2022 Tiso Alvarez Puccinelli