Paths Aliases

Instead of using relative import paths, which are often cumbersome, we can use path aliases:

- import { Counter } from '../../../../components/Counter'
+ import { Counter } from `#root/components/Counter`

where #root/ denotes our project's root directory.

We may need to define path aliases at up to three different places:

  • vite.config.js#resolve.alias (for files processed by Vite)
  • package.json#imports (for Node.js files not processed by Vite)
  • tsconfig.json#compilerOptions.paths (for TypeScript)



// vite.config.js

export default {
  resolve: {
    alias: {
     "#root": __dirname,

Only applies for files that are processed by Vite; some of our Node.js server files may not be processed by Vite, see the Node.js section below.


Example: /examples/path-aliases/vite.config.ts


// package.json

  "imports": {
    "#root/*": "./*.js" // Or `./*.ts` if using TypeScript


Example: /examples/path-aliases/package.json

Vite's vite.config.js#resolve.alias only applies to files that are processed by Vite. (All following files and their imports: *.page.js, *.page.server.js,*.page.client.js, *.page.route.js.)

Browser files are always processed by Vite, but this is not always the case for Node.js server files, for example Express.js server code.

For these files we can use Node.js's built-in support package.json#imports or, alternatively, we can use one of many npm packages such as module-alias. (Example of using module-alias: /examples/path-aliases (@c914dad).)


// tsconfig.json

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

If we use TypeScript, then TypeScript needs to know about our path aliases.


Example: /examples/path-aliases/tsconfig.json