TExcelTAD
Home › Vite › Vite Resolve Aliases

Vite Resolve Aliases

As a project grows, imports like ../../../components/Button.js become hard to read and break whenever a file moves. Aliases let you write @/components/Button.js instead.

Defining an alias

js
// 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)),
    },
  },
});

Now these two imports are equivalent anywhere in the project:

js
import { Button } from '../../../components/Button.js';
import { Button } from '@/components/Button.js';

Note: Alias targets should be absolute file-system paths. fileURLToPath(new URL('./src', import.meta.url)) or path.resolve(import.meta.dirname, 'src') both produce one.

How alias matching works

For an object alias, Vite checks whether the import starts with the key followed by / (or equals it exactly), and swaps that prefix for the target. This playground implements the rule:

js · try it yourself
const alias = {
  '@': '/home/me/app/src',
  '~assets': '/home/me/app/src/assets',
};

function resolveAlias(id) {
  for (const [find, replacement] of Object.entries(alias)) {
    if (id === find || id.startsWith(find + '/')) {
      return replacement + id.slice(find.length);
    }
  }
  return id; // untouched: relative path or a package name
}

const imports = ['@/utils/date.js', '~assets/logo.svg', './local.js', 'vue', '@vueuse/core'];
for (const id of imports) console.log(id.padEnd(18), '=>', resolveAlias(id));
@/utils/date.js    => /home/me/app/src/utils/date.js
~assets/logo.svg   => /home/me/app/src/assets/logo.svg
./local.js         => ./local.js
vue                => vue
@vueuse/core       => @vueuse/core

Notice that @vueuse/core is not touched: @vueuse does not start with @/. That's why @/ is a safe convention even though npm scoped packages also start with @.

Array form and regular expressions

For more control, pass an array of { find, replacement } objects. find can be a regular expression, and the replacement can use capture groups:

js
export default defineConfig({
  resolve: {
    alias: [
      { find: '@', replacement: '/src' },
      // "icons:check" -> /src/assets/icons/check.svg
      { find: /^icons:(.*)$/, replacement: '/src/assets/icons/$1.svg' },
      // swap a heavy library for a lighter one
      { find: 'lodash', replacement: 'lodash-es' },
    ],
  },
});

Array order matters: the first match wins.

js · try it yourself
const aliases = [
  { find: /^icons:(.*)$/, replacement: '/src/assets/icons/$1.svg' },
  { find: 'lodash', replacement: 'lodash-es' },
  { find: '@', replacement: '/src' },
];

function resolve(id) {
  for (const { find, replacement } of aliases) {
    if (find instanceof RegExp) {
      if (find.test(id)) return id.replace(find, replacement);
    } else if (id === find || id.startsWith(find + '/')) {
      return replacement + id.slice(find.length);
    }
  }
  return id;
}

console.log(resolve('icons:check'));
console.log(resolve('lodash/debounce'));
console.log(resolve('@/main.ts'));
/src/assets/icons/check.svg
lodash-es/debounce
/src/main.ts

Here /src works because Vite resolves root-relative paths against the project root.

Tell TypeScript about it

Vite knows the alias, but TypeScript and your editor do not. Mirror it in tsconfig.json with paths:

json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

Without this, tsc reports Cannot find module '@/components/Button' even though Vite runs fine.

Tip: Vite 8 can read paths from tsconfig.json directly with resolve: { tsconfigPaths: true }, so you only maintain the mapping in one place. Older projects use the vite-tsconfig-paths plugin for the same result.

Aliases in CSS and HTML

Aliases work everywhere Vite resolves paths — not only in JavaScript:

css
@import '@/styles/variables.css';

.hero {
  background: url('@/assets/hero.jpg');
}
html
<script type="module" src="@/main.ts"></script>

Other resolve options

Option Purpose
resolve.alias Path replacements (this lesson)
resolve.extensions Extensions tried for extension-less imports. Default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
resolve.dedupe Force a single copy of a package (e.g. ['react'] in monorepos)
resolve.conditions Extra conditions for package exports resolution
resolve.mainFields Fields of package.json tried for entry points

Warning: Don't add .vue or .svelte to resolve.extensions. Omitting extensions for non-JS files hurts IDE and type support; just write the extension.

Test yourself

With alias { '@': '/abs/src' }, what does @vueuse/core resolve to?

  1. /abs/srcvueuse/core
  2. /abs/src/vueuse/core
  3. It stays @vueuse/core
  4. An error

Vite runs fine but tsc reports "Cannot find module '@/utils'". What's missing?

  1. A Vite plugin
  2. A matching paths entry in tsconfig.json
  3. The .js extension
  4. A restart

In the array form of resolve.alias, which entry is used when several match?

  1. The last one
  2. The longest one
  3. The first one
  4. All of them in sequence