Code Analysis Tool Integration Practice — Integrate SonarQube with your React/npm project

Jeffrey Chen
2 min readJun 28, 2020

--

Sonar do NOT provide the npm Sonar Scanner officially, however we still can find an unofficial one to help us to integrate SonarQube with your npm project. In our demo project, we create an simple React project to practice.

*You can find the demo project from here.

  1. Create a token for your scanner to pass the authentication. Make sure you copy the token right after you generate it, you won’t be able to see it again!

2. Add an script file for executing Sonar Scanner

let sonarqubeScanner = require('sonarqube-scanner');

sonarqubeScanner({ serverUrl : "http://stg-sonar102.dsd.dev.rsc.local:9000", token : "1ad066960082a3247a8020dd24a19cc6cd8ebc14", options : { 'sonar.sources': 'src', 'sonar.tests': 'src', 'sonar.inclusions' : '**', // Entry point of your code 'sonar.test.inclusions': 'src/**/*.test.js', 'sonar.typescript.lcov.reportPaths': 'coverage/lcov.info', 'sonar.testExecutionReportPaths': 'coverage/test-reporter.xml', },}, () => process.exit());

3. Add script command and dependencies into package.json

{
...
"dependencies": {
...
"jest-sonar-reporter": "2.0.0",
"sonarqube-scanner": "2.6.0"

},
"scripts": {
...
"sonar": "node pipeline/sonar.js"
},
...
"jestSonar": {
"reportPath": "coverage",
"reportFile": "test-reporter.xml",
"indent": 4
}

}

4. Run the test command to generate the test and coverage report

npm test -- --coverage --testResultsProcessor=jest-sonar-reporter

5. Run the script to trigger Sonar Scanner, then you can find the project has been created on SonarQube automatically.

npm run sonar

It just cost a few step to integrate Sonarqube with you npm projects, however not all programming languages / build systems have such helpful package. So, next I will introduce how to use general Sonar Scanner to analyze your Python and Golang projects. See you.

--

--

Jeffrey Chen
Jeffrey Chen

Written by Jeffrey Chen

Software engineer who’s dream is to become an athletes

No responses yet