Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Project Structure and Config

Aliases and Path Resolution

Configure resolve.alias for clean imports like @/components, keep tsconfig paths in sync, understand resolve.extensions and conditions, and fix common "failed to resolve import" errors.

Deep relative imports such as ../../../components/Button.js are easy to break and hard to read. Aliases let you write @/components/Button.js from anywhere. Vite also decides how bare names, extensions and package entry points are resolved. This lesson covers resolve.alias, keeping TypeScript in agreement, and the errors you will meet when a path is wrong.

Vite is not installed on this site, so the config is read-only. The stand-ins model alias matching so you can test rules before using them.

resolve.alias

JavaScript
// vite.config.js
import { defineConfig } from 'vite';
import { fileURLToPath, URL } from 'node:url';

export default defineConfig({
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      '~assets': fileURLToPath(new URL('./src/assets', import.meta.url)),
    },
  },
});

Now these imports work anywhere:

JavaScript
import Button from '@/components/Button.js';
import logo from '~assets/logo.svg';

Use absolute paths for alias targets. A relative target such as './src' is resolved from wherever the importing file happens to run, and is a common source of mysterious failures. fileURLToPath(new URL('./src', import.meta.url)) or path.resolve(import.meta.dirname, 'src') are reliable.

The alias also applies inside CSS (@import '@/styles/vars.css') and url() references. For url() in CSS you may need a ~ or a different form depending on the preprocessor; see Sass, Less and PostCSS.

Array form with regular expressions

When you need more control (exact matching or capturing groups) use the array form:

JavaScript
resolve: {
  alias: [
    { find: /^@\/(.*)$/, replacement: '/src/$1' },
    { find: 'lodash', replacement: 'lodash-es' },
  ],
}

With the object form, '@' matches @ and anything beginning with @/. In the array form with a string find, the match is also by prefix. Rules are tried in order and the first match wins, so list specific rules before general ones.

A runnable alias matcher

This stand-in implements the matching idea from scratch, so you can see why order matters.

Node.js Stand-in: alias matching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice lodash/fp is untouched because the regex has $. And with the wrong order, the general @ rule shadows the specific one.

Keeping TypeScript in agreement

Vite resolves paths at build time; TypeScript resolves them in your editor for type checking. They are configured separately, and if they disagree you get either red squiggles with a working build, or the reverse. Mirror the alias in tsconfig.json:

JSON
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "~assets/*": ["src/assets/*"]
    }
  }
}

(Modern TypeScript can use paths without baseUrl; the targets are then relative to the tsconfig.json.) Some teams use the plugin vite-tsconfig-paths to read the paths so there is only one source of truth.

Node.js Stand-in: check that two alias maps agree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

resolve.extensions

When you import ./Button without an extension, Vite tries a list of extensions in order. The default list is ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']. Vue's .vue is deliberately not included: write ./App.vue in full. Each extra extension makes Vite check more files on disk for every extensionless import, so the Vite documentation advises against growing the list. For your own non-JavaScript files, always write the extension.

resolve.conditions and package exports

Modern packages declare entry points in package.json with an exports map and conditions such as import, require, browser, node, development, production:

JSON
{
  "name": "my-lib",
  "exports": {
    ".": {
      "browser": "./dist/browser.js",
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    }
  }
}

Vite picks the first matching condition from its own list (import, module, browser, default, and development|production by mode). If a library picks the wrong build, you can add to resolve.conditions. This is an advanced setting; most projects never need it.

Linking and monorepos

In a monorepo, packages in node_modules that are symlinks to workspace folders are treated as source code by Vite, not as dependencies. That means they are not pre-bundled and HMR works inside them. If a linked package imports something Vite cannot resolve, add it to optimizeDeps.include, or set resolve.dedupe to force one copy of a package (useful for React or Vue appearing twice and breaking hooks or reactivity):

JavaScript
resolve: {
  dedupe: ['react', 'react-dom'],
}

Debugging resolution errors

Message Likely cause Fix
Failed to resolve import "@/x" from "src/main.js" Alias missing, or target wrong Check resolve.alias, restart the server
Failed to resolve import "foo" Package not installed npm install foo
It works locally, fails on CI Different letter case in a filename Match the case exactly
Types complain but the build works tsconfig paths missing Mirror the alias in tsconfig.json
Two copies of a framework Linked package has its own node_modules Use resolve.dedupe

Restart the dev server after changing aliases; Vite restarts itself when it sees config changes, but cached resolutions in the browser may need a hard reload.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should alias targets be absolute paths?

    Use path.resolve or fileURLToPath so the alias always points at the same folder.
  2. 2. With the alias list [@ -> /src, @/components -> /src/ui], where does @/components/Button.js go?

    The first matching rule wins, so the general @ rule matches first. Put the more specific rule first.
  3. 3. Which file must you also update so your editor understands an alias?

    TypeScript resolves paths on its own, so mirror aliases in tsconfig paths (or use vite-tsconfig-paths).
  4. 4. What does resolve.dedupe help with?

    Libraries such as React or Vue break when two copies are loaded. dedupe makes Vite resolve them from the project root.

Summary

  • resolve.alias maps import prefixes such as @ to absolute folders; the first matching rule wins.
  • Mirror aliases in tsconfig.json paths so the editor and type checker agree.
  • resolve.extensions lets you omit common extensions; always write .vue and other asset extensions.
  • Package exports conditions are matched by Vite; resolve.dedupe avoids duplicate framework copies.
  • Most resolve errors are a missing alias, an uninstalled package or a filename case mismatch.

Next: TypeScript in Vite