Sonarqube on a Javascript Project

This article shows two distinct methods of running SonarQube against a Javascript Project running on our local machine, by the use of:
1. Docker
2. An npm module sonar-scanner.

The Docker’s way:

Have Docker installed on your machine, we are halfway through the process already!

To run Sonarqube server:

docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest

Browse localhost:9000 to view Sonarqube UI.
Log into the portal with username and password admin.

Configuring your Project:
Navigate to the root of the project to add a file named sonar-project.properties. This is the file that guides sonar-scanner to report the analysis to Sonarqube server.
This file needs a mandatory field sonar.projectKey
Add sonar.projectKey=<anyNameOfYourChoice>

Project Initialisation on Sonarqube Server
Once you are signed into the UI, create a project preferably by the same name as that of the projectKey. The next step is to generate a token. Save this token, it is required to run the scanner.

To run SonarScanner:
docker run --rm --network=host -e SONAR_HOST_URL="http://localhost:9000" -e SONAR_LOGIN="<yourTokenHere>" -v "$PWD:/usr/src" sonarsource/sonar-scanner-cli

We should now be able to see the results on Sonarqube.

2. sonar-scanner NPM Module

Alternatively, we can easily use sonar-scanner, the npm-module to run sonarqube against our Javascript project.

Install sonar-scanner as dev-dependency
npm install -D sonar-scanner

Configure an npm script in package.json to run the scanner

In the case of using sonar-scanner npm module, sonarServerUrl is either the one running locally http://localhost:9000 as described above(using docker), or the organisation’s sonarServer url with token.
Do not forget to have sonar-project.properties in the JS project root and creating a token if there isn’t one already.

npm run scan should now publish the result to sonarqube server.