Tue Mar 14 2023

Setup Aliases in Vite with Typescript

How to setup Aliases in Vite with Typescript to use absolute imports in your react projects.

Author: Cesar Gomez

React JsTypescriptVite

Why use Aliases?

we constantly need to import components, images, icons, etc. We usually do it by using relative imports meaning something like:

import GenericButton from '../../components/GenericButton';

and that’s ok but a soon as our import portion of the file starts to grow it becomes a little bit messy and hard to read. Thats why we can use Aliases to make our imports more readable and easier to maintain.

so we can pass from the previous example to something like this:

import GenericButton from '@components/GenericButton';

let’s see how to do it.

Setup your ts.config file

open you Typescript config file and add the following code

"baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@styles/*": ["src/styles/*"]
    },

so by setting the baseUrl property to ./ we are telling typescript to look for files starting at the same folder as the tsconfig.json.

then paths is just a series of entries that will reassign the imports that are relative to the baseUrl in other words it will replace src/ with @/ in our imports, as well as src/styles/ with @styles/.

Setup vite.config.ts

you’re done with your tsconfig.json but you still need to tell vite how to use the aliases you just created.

but before that, you need to install some modules from nodejs like path and his types if you are using Typescript, otherwise just install path.

#path + types for typescript

# yarn users
yarn add path @types/path
# npm users
npm i path @types/path

# just paths for javascript

#yarn users
yarn add path
#npm users
npn i path

with path and types done, open your vite.config.ts file and add the following code:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import path from 'path';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: true,
  },
  resolve: {
    alias: [
      { find: '@', replacement: path.resolve(__dirname, 'src') },
      {
        find: '@styles',
        replacement: path.resolve(__dirname, 'src/styles/'),
      },
      {
        find: '@components',
        replacement: path.resolve(__dirname, 'src/components/'),
      },
    ],
  },
});

which is telling vite how to resolve the aliases you created in your tsconfig.json file, you can continue adding more aliases as you need (@assets, @layout, @constants, etc.).

your done, now you can use aliases in your project!