Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

path-aliases.md

71 lines2.1 KB

1---
2id: path-aliases
3title: Path Aliases
4---
5​
6Path aliases are a useful feature of TypeScript that allows you to define a shortcut for a path that could be distant in your project's directory structure. This can help you avoid long relative imports in your code and make it easier to refactor your project's structure. This is especially useful for avoiding long relative imports in your code.
7​
8By default, TanStack Start does not include path aliases. However, you can easily add them to your project by updating your `tsconfig.json` file in the root of your project and adding the following configuration:
9​
10```json
12 "compilerOptions": {
13 "baseUrl": ".",
14 "paths": {
15 "~/*": ["./src/*"]
16 }
17 }
19```
20​
21In this example, we've defined the path alias `~/*` that maps to the `./src/*` directory. This means that you can now import files from the `src` directory using the `~` prefix.
22​
23After updating your `tsconfig.json` file, configure your build tool so it resolves the same path aliases.
24​
25<!-- ::start:tabs variant="bundler" -->
26​
27# Vite
28​
29Vite has [built-in support for path aliases](https://vite.dev/config/shared-options#resolve-tsconfigpaths), which is disabled by default. To enable it, add the following configuration to your `vite.config.ts` file:
30​
31```ts
32// vite.config.ts
33import { defineConfig } from 'vite'
34​
35export default defineConfig({
36 resolve: {
37 // This enables built-in support for path aliases defined in tsconfig.json
38 tsconfigPaths: true,
39 },
40})
41```
42​
43# Rsbuild
44​
45Rsbuild reads the `paths` field from `tsconfig.json` by default. No extra config is needed when your aliases live in the root `tsconfig.json`.
46​
47If you use a custom tsconfig file, point Rsbuild at it with `source.tsconfigPath`:
48​
49```ts
50// rsbuild.config.ts
51import { defineConfig } from '@rsbuild/core'
52​
53export default defineConfig({
54 source: {
55 tsconfigPath: './tsconfig.custom.json',
56 },
57})
58```
59​
60<!-- ::end:tabs -->
61​
62Once this configuration has completed, you'll now be able to import files using the path alias like so:
63​
64```ts
65// app/routes/posts/$postId/edit.tsx
66import { Input } from '~/components/ui/input'
67​
68// instead of
69​
70import { Input } from '../../../components/ui/input'
71```