How to create an import alias when using vite/typescript/react
March 24th, 2023

Import aliases can make code much more readable. Instead of having a line like import Grid from "./../../../../components/Grid"; you can instead have that line look like import Grid from "@/components/Grid";. This is much more readable and produces code that doesn't break if this file is moved around.

Every import alias setup is a bit different, so this one is specific to using vite with react and typescript.

Specifically, in this case we will have the @ symbol represent the root of the src/ directory. But you can use different symbols and map to different directories.

First, let's start by updating tsconfig.json to include the new paths mapping. This is what my tsconfig.json looks like:

{ "compilerOptions": { ... "paths": { "@/*": ["src/*"] } } }

Next, update vite.config.ts to include the new resolve.alias mapping. This is what my full vite.config.ts looks like:

export default defineConfig({ plugins: [react()], resolve: { alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }], }, });

For good measure, restart the vite dev server and you should be set. Now importing from @/ will be like importing from src/.