Why is the path alias I declared not resolved?

922 Views Asked by At

tl;dr: I am getting error TS2307 when importing a file via an alias path defined in tsconfig.json, even though I think the path should be correct.


The directory structure in my Angular/nx/TypeScript project looks like this:

project
  |- libs
  |    |- aaa
  |         |- bbb
  |              |- src
  |              |    |- lib
  |              |    |    |- ccc
  |              |    |         |- components
  |              |    |              |- ddd
  |              |    |                   |- ddd.component.ts
  |              |    |- index.ts
  |              |- tsconfig.json
  |- tsconfig.base.json

tsconfig.base.json defines global paths like this:

{
  ...
  "compilerOptions": {
    "rootDir": ".",
    ...
    "baseUrl": ".",
    "paths": {
      ...
      "@myproject/aaa/bbb": [
        "libs/aaa/bbb/src/index.ts"
      ],
      ...

This works as expected - I can import @myproject/aaa/bbb and access anything exported from index.ts. For example, if I export DddComponent (defined in ddd.component.ts) from index.ts, I can use

import {DddComponent} from '@myproject/aaa/bbb';

In tsconfig.json, I would like to offer aliases locally inside the aaa/bbb module. Using these aliases, it should be possible to directly access arbitrary files:

{
  "extends": "../../../tsconfig.base.json",
  ...
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      ...
      "@lib/ccc/*": [
        "./src/lib/ccc/*"
      ],
      ...

Now, in index.ts, if I write

import {DddComponent} from './lib/ccc/components/ddd/ddd.component';

there are no complaints. However, I would like to use my locally defined alias:

import {DddComponent} from '@lib/ccc/components/ddd/ddd.component';

(In fact, this is even what WebStorm's auto-completion suggests me to write when I start typing import {DddComponent}.)

However, using the latter import statement, the build will fail:

Error: libs/aaa/bbb/src/index.ts:1:28 - error TS2307: Cannot find module '@lib/ccc/components/ddd/ddd.component' or its corresponding type declarations.

I think this should work, yet it doesn't and I do not know why. Is there any way to make my alias work?

1

There are 1 best solutions below

1
Vijay On
{
  "extends": "../../../tsconfig.base.json",
  ...
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      ...
      "@lib/ccc/*": [
        "src/lib/ccc/*" <---- remove the './' prefix
      ],
      ...