Leveling Up Your React TypeScript Game: Mastering Path-Aliases for Cleaner Code

Introduction
The importing processes get confusing as your TypeScript React project expands, but everything is nicely organized in its folder. Mainly if you are using a react-bulletproof project structure, this is true. We have our components neatly in one place, functions in another, pages, routes, etc.; you name it. Though keeping track of files when we organize them is easy, the problem arises when we try to import them throughout our project.
After some time spent on organization, your project looks more like this with deeply nested folder structures where imports might look like:
import { Button } from "../../../components/Button";
Our problem is that the path contains far too many ../../../
statements, and if we aim for a higher structural level, the path may get even longer.
This is incredibly annoying because we will sometimes import from different levels, forcing us to attempt to figure out how to go to that other path by figuring out where we are.
Ready to improve your imports? Let’s get started!
Spoiler Alert:
After this article, this is how your imports are going to look like:
import { Button } from "@/components/Button";
Much cleaner, right?
Setting up a Path Alias
Using a path alias allows us to define a word or a path to represent its actual location. There are several ways to solve this issue. Surprisingly, even in 2023, when we have React 18, CRA v5, and Vite configurations, path aliases are still not supported out of the box.
For Vite Projects
If you’re using Vite, edit your vite.config.ts
:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src/'),
},
},
})
Then update your tsconfig.json
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
For Create React App (CRA) Projects
If you’re using Create React App, you’ll need to use react-app-rewired
:
npm install react-app-rewired
Create a config-overrides.js
file in your project root:
const path = require('path');
module.exports = function override(config, env) {
config.resolve.alias = {
'@': path.resolve(__dirname, 'src/'),
};
return config;
};
Update your tsconfig.json
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
Update your package.json
scripts:
{
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
}
}
Now when you run yarn start
voila! It works just fine with our cleaner imports.
Let me know if you had any issues while following this guide, I’ll be happy to help you out!