Skip to main content

Absolute Import

Setting up Absolute Imports with jsconfig

––– views

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

{ "compilerOptions": { "jsx": "preserve", "baseUrl": ".", "paths": { "@/*": ["*"] } }, "exclude": ["node_modules", ".next"] }
json

For Create React App

Add this to root with the filename of jsconfig.json

{ "compilerOptions": { "baseUrl": "./src", "jsx": "preserve", "paths": { "@/*": ["./src/*"], "@/components/*": ["./components/*"], "@/pages/*": ["./pages/*"], "@/contexts/*": ["./contexts/*"], "@/routes/*": ["./routes/*"] } }, "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