angulartypescripttsconfigtsconfig-pathstsconfig.json

Angular 16: unable to override "baseUrl" in tsconfig.app.json


I have created a new workspace using Angular CLI and added 2 projects to it, one lib and one application. Running the app "my-app" with "ng serve" works fine.

After copying .ts files over to the new "my-app" project I get compiler errors, and relative paths are not recognized:

import { environment } from 'environments/environment';

this only works if I change it to:

import { environment } from 'projects/my-app/src/environments/environment';

My project structure:

+ node_modules
+ projects
| + my-app
| | + src
| | | + app
| | | | - app.module.ts (etc.)
| | | + environments
| | | | - environment.ts
| | - tsconfig.app.json
- tsconfig.json
- package.json

So far I've tried to override "baseUrl" of tsconfig.app.json with many values, but none of them worked:

"projects/my-app/src"
"src",
"./src"

(using VS Code I restarted TS server many times: Ctrl + P > "Typescript: restart TS Server" with no effect; seems like TS compiler does not read tsconfig.app.json at all)

Setting "baseUrl" in the workspace's tsconfig.json file works:

workspace tsconfig.json:

...
"baseUrl": "./projects/my-app/src",
...

but since I'm going to add other projects to the workspace later, I prefer not to solve it this way.

I know about adding shortcuts to tsconfig.json > "paths", but I'd have to change hundreds, maybe thousands of .ts file import statements:

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@app/*": ["........"],
      "@pages/*": ["...../pages/*"],
      "@components/*": ["...../components/*"],
      "@state/*": ["...../state/*"]
    }
  }
}

How can I tell my Angular project's TS compiler that I've overridden baseUrl in tsconfig.app.json ?


Solution

  • Maybe you're looking for this (https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping and https://www.typescriptlang.org/tsconfig#paths):

    {
        "compilerOptions": {
            "baseUrl": ".",
            "paths" : {
                "*" : ["*", "projects/app1/src/*", "projects/app2/src/*"]
            }
        }
    }
    

    Please notice that paths are resolved relative to baseUrl. When setting baseUrl to a value other than ".", i.e. the directory of tsconfig.json, the mappings must be changed accordingly.

    This tells the compiler for any module import that matches the pattern "*" (i.e. all values), to look in two locations:

    1. *: meaning the same name unchanged, so map

    <moduleName> => <baseUrl>/<moduleName>

    1. projects/app1/src/* meaning the module name with an appended prefix, so map <moduleName> => <baseUrl>/projects/app1/src/<moduleName>

    Keep src in your paths depends only on your needs, just change them as you wish.