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?
Setting the
baseUrlto./srcmeans TypeScript starts looking for files from thesrcfolder. When we then use@src/to import files, TypeScript tries to find them within thesrcfolder, but that's not where the folder is located. By changing thebaseUrlto 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 thesrcfolder.So, when you import files, you can use the
@srcshortcut like this: