javascript - How to use absolute path with Typescript? - Stack Overflow

I have a project that written in Typescript on NodeJS. I am using relative path for my modules to impor

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?

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?

Share Improve this question asked Mar 5, 2020 at 12:34 Mümin Celal PinarMümin Celal Pinar 2053 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

There is a TypeScript feature that allows this.

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

{
  "pilerOptions": {
    // ...
    "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.

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

{
  "pilerOptions": {
    "baseUrl": "./src"
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742320293a4421673.html

相关推荐

  • javascript - How to use absolute path with Typescript? - Stack Overflow

    I have a project that written in Typescript on NodeJS. I am using relative path for my modules to impor

    11小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信