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';

And this is the clean import using absolute import:

import Nav from '@/components/Nav';

For Next.js

Add this to root with the filename of jsconfig.json

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

Or you can just use my Next.js & Tailwindcss starter template


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"]
}

And in craco.config.js

const path = require('path');
 
module.exports = {
  // ...existing code
  webpack: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
};