Edit

Paths Aliases

Instead of using relative import paths, which can be cumbersome, you can use path aliases. For example:

import { Counter } from '../../../../components/Counter'
import { Counter } from '#root/components/Counter'

We recommend following the Node.js convention to always prefix path aliases with the special character #.

If you use JavaScript, define your path aliases at:

If you use TypeScript, you must define your path aliases also at:

If Node.js runs your server code directly (you use neither +server.js nor +serverEntry.js), also define them at:

vite.config.js

// vite.config.js
 
export default {
  resolve: {
    alias: {
      '#root': __dirname
    }
  }
}
// vite.config.ts
 
import type { UserConfig } from 'vite'
 
export default {
  resolve: {
    alias: {
     "#root": __dirname,
    }
  }
} satisfies UserConfig

See also:

The Vite config resolve.alias only applies to files that are processed by Vite.

The following are processed by Vite:

Config files, such as vite.config.js or +config.js aren't processed by Vite. See Config files.

tsconfig.json

If you use TypeScript, then TypeScript needs to know about your path aliases.

// tsconfig.json
 
{
  "compilerOptions": {
    "paths": {
      "#root/*": ["./*"]
    }
  }
}

See also:

package.json

Defining path aliases at package.json#imports is usually not needed: if you use +server.js or +serverEntry.js, then Vite processes your server code and resolves your path aliases (Node.js doesn't see any path alias).

It's only needed if:

In that case, also define your path aliases at:

// package.json
 
{
  "imports": {
    // JavaScript:
    "#root/*": "./*.js",
    // TypeScript:
    "#root/*": "./*.ts"
  }
}

This tells Node.js how to resolve path aliases (Node.js doesn't know about vite.config.js).

See also:

Alternatively, instead of using Node.js's built-in support over package.json#imports, you can use an npm package such as module-alias.

Config files

To make path aliases work in config files, such as +config.js and vite.config.js, define them at tsconfig.json or package.json (defining them in vite.config.js doesn't work for config files).

Config files are transpiled by Rolldown instead of Vite — Rolldown supports path aliases defined over tsconfig.json and package.json (Rolldown doesn't know about vite.config.js).