Clean way of importing using Absolute Import

Sadat Jubayer
August 25, 2022
• 2 min read
While working on a large project, importing files can be very nested or longer. Importing a file can be like this ./../../.. which looks wired. Absolute Imports and Module path aliases make these imports cleaner.
Without Absolute Imports
import Button from '../../components/button';
import Auth from '../context/auth';
With Absolute Imports
import Button from '@components/button';
import Auth from '@context/auth';
Let's know how to add these on React and NextJS projectse.preventDefault()
React
- Create a file
jsconfig.json
on the root directory and add these lines:
{
"compilerOptions": {
"baseUrl": "./src",
"jsx": "preserve",
"paths": {
"@/*": ["./src/*"],
"@/components/*": ["./components/*"],
"@/contexts/*": ["./contexts/*"]
// Add more folders based on your project
}
},
"exclude": ["node_modules", "build"]
}
Next.JS
- Create a file
jsconfig.json
on the root directory and add these lines:
{
"compilerOptions": {
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@/components/*": ["./components/*"],
"@/contexts/*": ["./contexts/*"]
// Add more folders based on your project
}
},
"exclude": ["node_modules", ".next"]
}
For TypeScript, the codes are the same. You just need to paste this one on a tsconfig.json
file.