tsconfigtsconfig-paths

Multiple values in tsconfig's paths


I currently have the following tsconfig.json:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "target": "ESNext",

    "paths": {
      "@common": [
        "./common",
        "../common",
      ],
      "@common/*": [
        "./common/*",
        "../common/*",
      ],
    },
  }
}

When I try to import something from ./common (using the @common alias) it works perfectly fine, but if I try to import something from ../common (using the @common alias) I get an error saying @common has no export member [name].

If I reverse the order of the array it's the other way round, I can import exports from ../common just fine but not from ./common.

Repro: https://stackblitz.com/edit/vitejs-vite-nnc4wb?file=src%2Findex.ts%2Ctsconfig.json

It seems that tsconfig.json only uses the first item of the array, is this intended or am I doing something wrong? If using only the first item of the array is intended behavior what's the point of having it be an array?


Solution

  • I'm facing the same problem but in a different environment (nestjs). I've checked the typescript compiler documentation here. If you look at the fallback paragraph it say:

    Multiple file paths can be provided for a path mapping. If resolution fails for one path, the next one in the array will be attempted until resolution succeeds or the end of the array is reached.

    After the first entry on the "@common" array it move on to the next one. The problem I had on my project was relative to the baseUrl option in extended configuration. Using the full path string as fallback I resolve the issue:

    # tsconfig.app.json
    
    {
      "extends": "../../tsconfig.json",
      ...
      "paths": {
        "@/*": [
          "src/*",
          "apps/crud/src/*"
        ],
      }
    }
    

    My project folders structure was:

    apps
    ├──crud
    ├──├──src
    ├──├──├──foo.ts
    ├──cli
    ├──├──src
    ├──├──├──bar.ts
    ├──├──tsconfig.app.json
    tsconfig.json
    

    I hope can be helpful.