How to integrate SonarQube with react application in Jenkins pipeline?

SonarQube is still one of the top tools for code quality and code security. Over the years it has matured and made a top place in the developer community.

The Java-based eco system has grater familirities with SonarQube code analysis.

ReactJS based frontend application usually uses eslint in the code editor. This is one way of code quality.

If we have a Jenkis pipeline and we are building the ReactJS application using Jenkins then we can easily integrate SonarQube quality gate along the way.

We need to have a profile in SonarQube. The profile needs to be associated with JavaScript rules. Once we have the profile ready in SonarQube, we can add the following stages in the Jenkins pipeline:

stage('Test') {
    steps {
        sh 'npm install'
        sh 'npm run test:once -- --coverage'
    }
}

stage('SonarQube analysis') {
    when {
        expression { build.deployEnv == 'dev' }
    }
    steps {
        script {
            z.sonarqube.scan(
                sonarQualityProfiles: ["typescript": "SonarQube Profile"],
                sonarOpts: [
                    'sonar.projectKey': '',
                    'sonar.sources': './src',
                    'sonar.cpd.exclusions': '**/*-mock.ts',
                    'sonar.javascript.lcov.reportPaths': './coverage/lcov.info',
                ]
            )
        }
    }
}
Reference