Edit this page

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 you use a custom server integration (you don't use vike-server), 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:

  • All client-side code.
  • All + files loaded at runtime (client or server).
  • Your server code if you use vike-server.

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

If you use a JavaScript server, with a custom integration instead of using vike-server, then 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:

If you use vike-server, all your server code is transpiled by Vite. Defining path aliases at vite.config.js is enough because Vite already resolves all path aliases and Node.js doesn't see any path alias.

If you don't use vike-server, your server code isn't processed by Vite out of the box. Instead, Node.js directly executes your server code and, therefore, you must configure Node.js to resolve your path aliases. See also: #562 - Transpile server code.

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 esbuild instead of Vite — esbuild supports path aliases defined over tsconfig.json and package.json (esbuild doesn't know about vite.config.js).