Absolute Imports In Vite React Typescript
![Absolute Imports In Vite React Typescript](/_next/image?url=%2Fimages%2Fblog%2Freact-vite-ts.png&w=1920&q=75)
Problem
Relative imports are the default way to reference source files in JavaScript projects. such as import Button from "../../../components/Button";
But when we are developing React applications,
importing files will be terrible when the applications are bigger because of the level of complexity and file structure,
Even more if in the future, we do refactoring or restructure files and directories we must update every import command.
Solution
update yout code as example below:
// vite.config.ts
export default defineConfig({
resolve: {
alias: {
'@': '/src' // Set the alias to the root of your "src" directory
}
}
// ... other configuration
})
// tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
// ... other configuration
}
Usage
import Layout from '@/Components/Layout.tsx'
Thanks you 😊