How to Use 'Absolute Import' in Next Js Application

Β·

2 min read

πŸ€” Why do we need this?

Well! You must have experience if you have built some components and have used them in any other component and later you want to shift from one place to another (they can be nesting), the compiler will ask you to change the location of that component in import by adding ../ or removing extra dots. So to avoid that problem, we can use absolute import, which helps in auto-import as well.

πŸ—‚ File Structure

πŸ—‚root
  πŸ—‚layout
    πŸ“PageGutter.tsx 
  πŸ—‚pages
   πŸ“checkout.tsx

🫠 Problem (Using Relative Import)

This is the actual component that is being used on every page

// layout/PageGutter
import { Box, BoxProps } from '@chakra-ui/react'
import React, { FC } from 'react'

interface Props extends BoxProps {}
const PageGutter:FC<Props> = ({ ...restProps }) => {
  return (
    <Box py="16" {...restProps} />
  )
}

export default PageGutter

This is the checkout page that uses relative import ../layout/PageGutter

// pages/checkout
import React from 'react'
import PageGutter from '../layouts/PageGutter';  // pain point πŸ˜₯

const checkout = () => {
  return (
    <PageGutter />
  )
}

export default checkout

πŸŽ‰ Solution (Using Absolute Import)

  1. The baseUrl configuration option allows you to import directly from the root of the project.

    // tsconfig.json or jsconfig.json
    {
     "compilerOptions": {
       "baseUrl": "."
     }
    }
    
  2. Importing same PageGutter.tsx component in checkout.tsx page using absolute import.

    // pages/checkout
    import React from 'react'
    import PageGutter from 'layouts/PageGutter';  // Omit dots 😎
    
    const checkout = () => {
     return (
        <PageGutter />
      )
    }
    
    export default checkout
    

Using an Alias (Optional)

Using paths allows you to configure module aliases. For example @/components/* to components/*.

  1. Configuration using an alias.
    // tsconfig.json or jsconfig.json
    {
     "compilerOptions": {
       "baseUrl": ".",
       "paths": {
         "@/layouts/*": ["layouts/*"]
       }
     }
    }
    
  2. Importing same PageGutter.tsx component in checkout.tsx page using absolute import but with alias.

     // pages/checkout
     import React from 'react'
     import PageGutter from '@layouts/PageGutter';
    
     const checkout = () => {
       return (
         <PageGutter />
       )
     }
     export default checkout
    

🎯 Conclusion

  1. Open tsconfig.json or jsconfig.json file in the root of your project.
  2. Configure tsconfig.json or jsconfig.json file by adding baseUrl and paths.
  3. Start using absolute imports.

πŸ‘‹πŸ½ Hope you enjoyed it, comment section is open, you are welcome, let's communicate there 🀝

Β