Auto-import in VSCode to respect *both* relative paths and tsconfig.json paths
Asked Answered
D

2

6

In this issue a recommendation is made to define this setting field:

"typescript.preferences.importModuleSpecifier": "relative"

In order to switch VSCode's auto-import behavior from absolute to relative. This:

import { Logo } from 'src/components/Logo';

becomes:

import { Logo } from '../../components/Logo';

Which is the desired auto-import behavior for us.

However, by changing this setting the auto-import mechanism starts ignoring the tsconfig.ts and instead of importing packages:

import { Button } from '@scope/base-ui';

it also imports files relatively:

import { Button } from '../../../packages/src/base-ui';

Is there a way to enjoy the best of both worlds?

Disaccord answered 10/1, 2022 at 2:31 Comment(0)
P
4
"typescript.preferences.importModuleSpecifier": "shortest"

This will pick an absolute import (including tsconfig-defined paths) if one is available that has fewer path segments than the relative path. If no absolute path is shorter, VS Code will use the relative path.

Prokofiev answered 18/8, 2022 at 21:27 Comment(0)
A
1

There's a "project-relative" option now.

Prefers a non-relative import only if the relative import path would leave the package or project directory. Requires using TypeScript 4.2+ in the workspace.

See https://code.visualstudio.com/docs/getstarted/settings

Ashtoreth answered 26/10, 2022 at 22:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.