Clean way of importing using Absolute Import

Sadat Jubayer

Sadat Jubayer

April 25, 2021

1 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

index.jsx
import Button from '../../components/button'
import Auth from '../context/auth'

With Absolute Imports

index.jsx
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:
jsconfig.json
{
  "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:
jsconfig.json
{
  "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 a tsconfig.json file.