Paths Aliases

Instead of using relative import paths, which are often cumbersome (e.g. import { Counter } from '../../../../components/Counter'), we can use path aliases.

// `~/` denotes our project root directory
import { Counter } from `~/components/Counter`


We can define path aliases with Vite at vite.config.js#resolve.alias.

// vite.config.js

export default {
  resolve: {
    alias: {
     // We can now `import '~/path/to/module'` where `~` references the project root
     "~": __dirname,

It applies only 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.



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

// tsconfig.json
  "compilerOptions": {
    "paths": {
      "~/*": ["./*"]



Vite's vite.config.js#resolve.alias only applies to files that are processed by Vite. In other words: **/*.page.js, **/*.page.server.js, **/*.page.client.js, **/*.page.route.js, and their imports.

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 a Node.js aliasing tool such as:

Example of using module-alias:

Edit this page