網站搜尋

SonarQube:TypeScript baseUrl 和相對路徑配置 => 問題 “依賴應明確” (typescript:S4328)


上下文

  • 使用的 ALM:Azure DevOps
  • 使用的 CI 系統:Azure DevOps
  • 適用時使用的掃描器指令(私人資訊已隱藏) :
  - task: SonarCloudPrepare@1
    inputs:
      SonarCloud: 'SonarCloud-Clement'
      organization: 'assoconnect'
      scannerMode: 'CLI'
      configMode: 'manual'
      cliProjectKey: 'assoconnect_frontend'
      cliProjectName: 'frontend'
      cliProjectVersion: '$(Build.BuildNumber)'
      cliSources: 'src'
      extraProperties: |
        sonar.tests=src
        sonar.test.inclusions=**/__tests__/**
        sonar.coverage.exclusions=src/pages/**
        sonar.junit.reportPaths=junit.xml
        sonar.typescript.lcov.reportPaths=coverage/lcov.info
        sonar.typescript.tsconfigPath=tsconfig.json
    displayName: 'Prepare SonarQube analysis'

  - task: SonarCloudAnalyze@1
    displayName: 'Run SonarQube analysis'

  - task: SonarCloudPublish@1
    inputs:
      pollingTimeoutSec: '300'
    displayName: 'Publish SonarQube analysis result'
  • 儲存庫的語言:TypeScript

觀察到問題

對於我們在 .tsx 文件中的所有 imports,我們都有“依賴應該是明確的 (typescript:S4328)”問題的實例。

我們在 tsconfig.json 文件中配置了 baseUrl (https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url),這樣我們就不必處理相對路徑。WebStorm 對這個配置似乎沒有問題,且 linter 不會顯示任何訊息。但在 Sonar 中,當我們導入一個模組時,由於沒有加上 ./ 前綴,它會認為這是一個外部模組,並在依賴中尋找它。

例子

  • 我們的佈局是:
src/
|___pages/
|   |___Index/
|       |___index.tsx
|       |___type.tsx
|___App.tsx
package.json
tsconfig.json
  • 檔案內容
// package.json
// nothing path-related, only external dependencies
...
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src/",
...
// src/App.tsx
...
import Index from 'pages/Index' // => ISSUE : Dependencies should be explicit (typescript:S4328)
...
// src/pages/Index/index.tsx
...
import * as Type from './type' // => OK, NO ISSUES
...
import { StoreContext } from 'store' // => ISSUE : Dependencies should be explicit (typescript:S4328)
...
export default () => (
...

答案#1

你可以嘗試在 sonar.sources 中添加特定路徑,如下所示:

// in my tsconfig
"paths": {
      "src": [
        "./src/*"
      ],
    },

// in my sonar-project.properties
sonar.sources=src/components,src/navigation,src/screens,src/store,src/types,src/utils

對我來說有效,在 Sonar 掃描報告中,“應明確依賴”的問題已被移除