Typescript path module resolution is not working

43 Views Asked by At

I am using Express JS and Typescript. I am trying to implement a modular pattern.

tsconfig.json

{
 "include": ["src"],
 "exclude": ["node_modules"],
 "compilerOptions": {
   "target": "es2016",
   "module": "commonjs",
   "rootDir": "./src",
   "moduleResolution": "node",
   "baseUrl": "./src",
   "paths": {
     "@src/*": ["src/*"]
   },
   "outDir": "./dist",
   "esModuleInterop": true,
   "forceConsistentCasingInFileNames": true,
   "strict": true,
   "skipLibCheck": true
 }
}

src/modules/stuedent/student.interface.ts

export type UserName = {
    firstName: string;
    //...
  };
  
  export type Guardian = {
    fatherName: string;
    //...
  };
  
  export type LocalGuardian = {
    name: string;
    //...
  };
  
  export type Student = {
    id: string;
    name: UserName;
    guardian: Guardian;
    localGuardian: LocalGuardian;
    //...
  };
  

src/modules/stuedent/student.module.ts

import { Guardian, LocalGuardian, Student, UserName } from './student.interface'; 

The above works fine

import { Guardian, LocalGuardian, Student, UserName } from '@src/student/student.interface'; 

The above shows error: Cannot find module '@src/student/student.interface' or its corresponding type declarations.

I want to perform the imports using @src.

How do i do it with modular path resolution?

1

There are 1 best solutions below

2
RogueMan On

Setting the baseUrl to ./src means TypeScript starts looking for files from the src folder. When we then use @src/ to import files, TypeScript tries to find them within the src folder, but that's not where the folder is located. By changing the baseUrl to just ./, TypeScript starts searching from the project's main folder. This way, when we use @src/ in our imports, TypeScript knows to search the entire project for the src folder.

{
  "include": ["src"],
  "exclude": ["node_modules"],
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDir": "./src",
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "@src/*": ["src/*"]
    },
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

So, when you import files, you can use the @src shortcut like this:

import { Guardian, LocalGuardian, Student, UserName } from '@src/modules/student'