Why does VS Code suggest me auto-imports via relative path instead of the path alias I defined in my tsconfig.json?
Asked Answered
D

2

5

My project structure is like this:

---- apps
---- libs
-------- index.ts
-------- commmon
-------- service
------------ index.ts
------------ src
---------------- index.ts
---------------- goods
-------------------- index.ts
-------------------- src
------------------------ index.ts
------------------------ goods.service.ts

enter image description here

Each index.ts have an export * from '...' statement.

And my tsconfig.json is down below:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "paths": {
      "@frosticx/library": [
        "libs"
      ]
    }
  }
}

I expect all import from libs should be import { ... } from '@frosticx/library';, However Vistual Studio does not regonize this path alias: enter image description here

Manually specify @frosticx/library would work, but as you can see Visual Studio does not treat it as a module: enter image description here

Dole answered 23/3, 2023 at 8:33 Comment(1)
B
9

Try setting "typescript.preferences.importModuleSpecifier": "non-relative" in your settings.json file. The default value of that setting is "shortest", which might be the problem here, since your alias seems to be longer than the relative path the module can be imported by.

Note: google-search suggestion: github typescript issues auto import use tsconfig paths.

Begonia answered 23/3, 2023 at 8:46 Comment(1)
Thank you for the suggestion. However it does not work unfortunately, Visual Studio does not seems to recognize to @frosticx/library. The only suggestion is libs/serviceDole
D
0

I changed paths to this and it seems to work:

"paths": {
      "@frosticx/library": [
        "libs",
        "libs/*"
      ]
    }

I have no idea why it works, but seems to be an ugly solution.

Update:

This even makes ../xxx to be @frosticx/library which is not expected.

Dole answered 23/3, 2023 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.