Always use alias for automatic imports
Asked Answered
C

2

6

Is there a way to force autoimport to always use the alias for importing modules in a [email protected] project using VSCode?

I would like to use them even when it's a sibling component, no exceptions, so instead of

import { Navbar } from "./components";

I would like to force auto-import to use the alias in all cases:

import { Navbar } from "@/components";
Collette answered 18/10, 2023 at 7:39 Comment(0)
I
15

Assuming you have your tsconfig.json (or jsconfig.json) setup for path aliases correctly, you can change VSCode's preferences in your User Settings. Search for "Import Module Specifier" and you should see two entries - one for TypeScript and one for JavaScript. To always use the path alias, change these to non-relative.

settings to change in vscode

If you prefer editing your settings.json directly, the keys are:

{
  //...
  "typescript.preferences.importModuleSpecifier": "non-relative",
  "javascript.preferences.importModuleSpecifier": "non-relative",
  //...
}

If you want to do this at a per-project level, instead change these for your Workspace Settings.

Interment answered 26/1 at 20:20 Comment(0)
A
-4

The purpose of alias is to simplify import of your functions/classes/etc.

Instead of typing:

import { Navbar } from "./../../../components";

You can create an alias to, for example, components:

import { Navbar } from "@/components";

The aliases are relied to your compiler options - jsconfig.json (tsconfig.json).

Here is example of jsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@components/*": ["components/*"],
      // Add more aliases as needed
    }
  }
}

You can find more info here

Alveta answered 18/10, 2023 at 13:42 Comment(2)
I'm aware of what aliases are for. I just want to force auto-import to always use aliases. It sometimes uses relative paths when auto-importing.Collette
Probably I didn't understand your comment correctly. You like to use only aliases, but this is your "developer side". Your environment, once you set the aliases will propose to use it as auto-import (for example, VSCode). Nextjs and JS don't care about your imports, finally before JS executes the code all "paths" will be absolute, aliases are designed for "human purposes"Alveta

© 2022 - 2024 — McMap. All rights reserved.