Absolute Import is a great way to clean up your imports
Example
This is the usual way of importing with ..
operator to go back 1 folder:
import Nav from '../../components/Nav';
jsx
And this is the clean import using absolute import:
import Nav from '@/components/Nav';
jsx
For Next.js
Add this to root with the filename of jsconfig.json
Or for typescript edit tsconfig.json
{
"compilerOptions": {
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"@/*": ["*"],
"~/public/*": ["./public/*"]
}
},
"exclude": ["node_modules", ".next"]
}
json
For Create React App
Add this to root with the filename of jsconfig.json
Or for typescript edit tsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"jsx": "preserve",
"paths": {
"@/*": ["./src/*"],
"@/components/*": ["./components/*"],
"@/pages/*": ["./pages/*"],
"@/routes/*": ["./routes/*"],
"~/public/*": ["./public/*"]
}
},
"exclude": ["node_modules", "build"]
}
json
And in craco.config.js
const path = require('path');
module.exports = {
// ...existing code
webpack: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
};
js