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:
-
tsconfig.json>compilerOptions.pathsYou must define them twice — inside
vite.config.jsandtsconfig.json. (It's temporary: Vite will soon support path aliases set intsconfig.json.)
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 UserConfigSee also:
The Vite config
resolve.aliasonly 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
+server.jsor+serverEntry.js.Config files, such as
vite.config.jsor+config.jsaren'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:
- Node.js runs your server code directly: you use neither
+server.jsnor+serverEntry.js(seerenderPage()> Without+serverEntry.js). - You use path aliases in config files and you don't define them in
tsconfig.json, see Config files.
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 asmodule-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.jsonandpackage.json(Rolldown doesn't know aboutvite.config.js).