How to setup path aliases in tanstack-start project
When working on a project using TanStack Start, organizing your codebase efficiently can save you a lot of time and effort. One common approach to improving project structure is using path aliases. With path aliases, you can replace long and repetitive relative imports like ../../../components
with clean and readable paths such as @/components
.
Step 1: Define Path Aliases in tsconfig.json
The first step is to configure your TypeScript path aliases in the tsconfig.json
file. This allows the TypeScript compiler to recognize the alias paths during development and compile time.
- Open your
tsconfig.json
file (or create it if it doesn’t exist). - Add the following configuration:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["app/*"]
}
}
}
Step 2: Configure Vite in app.config.ts
While configuring tsconfig.json
is essential, it’s not enough for TanStack Start projects. TanStack Start uses Vite as its build tool, which also needs to understand your aliases. To bridge the gap, you need to add the alias configuration to app.config.ts
.
Here’s how you do it:
- Open (or create) the
app.config.ts
file in your project root. - Add the alias configuration under the
vite
property:
// app.config.ts
import { defineConfig } from '@tanstack/start/config'
export default defineConfig({
vite: {
resolve: {
alias: {
'@': '/app',
},
},
},
})
This article is part of my TanStack Start series, where I build a project from scratch using TanStack Start. If you’re looking to learn more about setting up and scaling projects with TanStack Start, stay tuned for future articles in this series. You can subscribe for free and receive emails when new posts drop.
Happy coding! 🚀
Member discussion