How to setup path aliases in Vite (2,3) & Typescript
As of August 2023, this approach still works with Vite version 2 and 3. So whenever I mention Vite, I am referring to the version 2 and 3. Let me know if you encounter any problems in the comment section.
Have you ever thought of how to get rid of imports that look like ../../assets/*
or ../../../assets/*
.
Reasons you need this
- Simplify referencing the project root.
- Address module resolution errors when modifying files in directories.
- Satisfy your curiosity
In this tutorial, I will be using the alias @
as a reference to the root of the project. In order to follow this tutorial, you need to scaffold a react project using Vite. Although I am using react to demonstrate this, you can do the same for other front-end frameworks like Vue and AngularJS as long as Typescript is supported.
Click here to learn more about how to scaffold a new Vite app. Follow the following steps to set a path alias for both typescript and Vite
Steps to take
- In your project directory, open
tsconfig.json
file and add the following entries to thecompilerOptions
key. Usually your project root has a src folder where all the source codes exist at. Set it as the base url.
{
"compilerOptions": {
...//other configs
"baseUrl": "src",
"paths":{
"@/*": ["./*"]
}
}
}
For more information on typescript paths mapping & module resolution heuristics configuration: Click here
The above configuration, informs typescript of to map module names, that matches the glob pattern @/*
to src/*
, preserving the other paths information at run-time.
Please notice that paths are resolved relative to baseUrl.
- The next step is to update your Vite configuration file,
vite.config.ts
file to the following.
// ...other imports
import {resolve} from "path";
export default defineConfig(() => ({
// ... other configurations
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
}
}))Do not forget to install `@types/node` for good better type checking node
Before:
import { useState } from "react";
import reactLogo from "./asset/react.svg";
import "./App.css";
Now:
import { useState } from "react";
import reactLogo from "@/asset/react.svg";
import "@/App.css";
Thank you for reading thus far. Your application should continue functioning correctly. Feel free to explore other configuration options. If this guide was useful, let me know by commenting, sharing and giving a thumbs up.