Using relative imports can get messy in no time, especially in large, complex projects. Moving from relative paths like ../../../components/Button makes your code cleaner and easier to refactor.
However, if you're working with Vite and TypeScript, simply updating your tsconfig.json isn't enough. You have to ensure both the TypeScript compiler and the Vite build tool are on the same page. Here is the most direct way to set it up.
Step 1: Update your TypeScript Configuration
In recent Vite templates, the tsconfig.json file often acts as a base configuration that references other files. To follow this project structure correctly, you should place your path aliases inside tsconfig.app.json.
Handling the "baseUrl" Deprecation
A common issue developers face is the deprecation of baseUrl in newer versions of TypeScript. You have two ways to handle this:
Option A: The Modern Approach (Recommended) Remove baseUrl entirely and use paths relative to the configuration file. Notice the ./ prefix in the path:
{
"compilerOptions": {
"composite": true,
"paths": {
"@/*": ["./src/*"]
}
}
}
Option B: The Legacy Workaround If you must use baseUrl, you will need to silence the deprecation warning:
{
"compilerOptions": {
"ignoreDeprecations": "5.0", // Use 5.0 or 6.0 depending on your TS version
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
}
Step 2: Update your Vite Configuration
While TypeScript now understands what @/ means for autocompletion and type checking, Vite still doesn't know how to resolve that alias during the actual build or dev process.
Open your vite.config.ts file and add the resolve.alias property:
export default defineConfig({
// other configurations
resolve: {
alias: {
'@': '/src',
},
},
})
Why do we need both?
It's helpful to remember the roles of these two files:
-
tsconfig.json: Tells VS Code and the TypeScript compiler how to find files so you get "Click to Definition" and no red squiggly lines. -
vite.config.ts: Tells the Bundler how to actually grab the code and put it in the browser.
By syncing these two files, you get a seamless development experience with clean, absolute imports.
The End!
Top comments (0)