Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use absolute path with Typescript?

I have a project that written in Typescript on NodeJS. I am using relative path for my modules to import another. But this usage is getting dirty while project is growing. Because of that I want to convert relative paths to absolute path.

Here is my project folder structure:

src
├── controllers
├── repositories
├── services
│   ├── user.service.ts
|── tsconfig.json

I want to use import another module like below.

import userServices from "src/services/user.service";

tsconfig.json

"moduleResolution": "node",
"baseUrl": ".",
"paths": {
  "*": ["src/*"]
}

Above configurations is not working on my workspace.

Could you help me about that?

like image 897
Mümin Celal Pinar Avatar asked Aug 11 '26 16:08

Mümin Celal Pinar


2 Answers

There is a TypeScript feature that allows this.

You can modify your src/tsconfig.json file to enable this, under compilerOptions, add the following:

{
  "compilerOptions": {
    // ...
    "paths": {
      "*": [
        "./*",
        "app/*",
        "../node_modules/*"
      ]
    }
}

You can obviously change the pattern key and values as needed. You add or remove folders, you can change the order, etc.

You can also choose a prefix instead of just * (especially if it cases problems), you can use something like ~/*, and your imports will then be all from '~/shared/sample' etc.

like image 157
Sanjay Lohar Avatar answered Aug 14 '26 07:08

Sanjay Lohar


Add this in your tsconfig. Change the path as required by you

{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}
like image 41
joy08 Avatar answered Aug 14 '26 07:08

joy08



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!