Enable the @ alias syntax in your Vite + React project
- Get link
- X
- Other Apps
To enable the @
alias syntax in your Vite + React project (so you can import files like @/components/Button
), you need to configure path aliases in two places:
----------> THIS WAY IS FOR JAVASCRIPT IN REACT + VITE
Run this Command => npm i path
✅ 1. Configure Vite Alias
In your vite.config.js
:
import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'import path from 'path'import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
// https://vitejs.dev/config/export default defineConfig({ plugins: [react()], resolve: { alias: { '@': path.resolve(__dirname, './src'), }, },})
✅ 2. Update jsconfig.json
Use jsconfig.json
for JavaScript.
(NOTE -> if u already dont have jsconfig.json then craete it in root where u craete .env file)
Add or update:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
✅ 3. Restart the Vite dev server
After these changes, restart your dev server:
npm run dev
Now you can use in any file:
import Button from '@/components/Button'
----------> THIS WAY IS FOR TYPESCRIPT IN REACT + VITE
1. Configure Vite (vite.config.ts)
Open your vite.config.ts
file and modify it to include the alias configuration:
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'),
},
},
})
2. Configure TypeScript (tsconfig.app.json)
Since you have a project structure with separate tsconfig files, you need to edit tsconfig.app.json
(not the main tsconfig.json). Open tsconfig.app.json
and add the path mapping:
{
"compilerOptions": {
// ... your existing options like target, lib, etc. ...
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
// ... rest of your existing options ...
},
// ... rest of your config like include, etc. ...
}
3. Install @types/node (if needed)
If you get an error about __dirname
not being defined, install Node.js types:
npm install -D @types/node
4. Leave tsconfig.json unchanged
Your main tsconfig.json
should stay exactly as it is:
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
5. Restart your development server
After making these changes:
npm run dev
6. Usage
Now you can use the @
alias in your imports:
// Instead of relative imports:
import App from './App'
import something from '../../../components/Button'
// You can use:
import App from '@/App'
import something from '@/components/Button'
The @
will always point to your src
folder, making imports cleaner and easier to manage regardless of how deeply nested your files are.
- Get link
- X
- Other Apps
Comments
Post a Comment