How to Import Components using Absolute Imports in Next JS

The Next JS can be considered as a better version of React JS. It provides a lot of useful utility for developing Static and Single Page websites.

But the problems we face related to imports is the same as compared to React JS and to switch from relative to absolute imports follow the below steps:

  1. Create an jsconfig.json in the root of your project.
  2. Add the below-provided snippet in jsconfig.json file.
                {
                    "compilerOptions": {
                        "baseUrl": ".",
                        "paths": {
                            "@/com/*" : [ "components/*" ],
                        }
                    }
                }
    

    The @/com/ is the alias path to access the component. This means instead of importing import Cart from '../../carts/cart' will change to import Cart from '@/com/carts/cart'.

    The At sign ( @ ) in jsconfig.json is just a symbol. Instead of @ you can use other text.Example:
    import Cart from 'ANY/com/carts/cart' and make the changes in jsconfig.json as "ANY/com/*" : [ "components/*" ],.

    Note

    The server must be reloaded every time you update or make modifications in jsconfig.json file.

  3. After Changes Restart the server using npm run dev
Snippet of jsconfig.json file configuration for absolute imports in Next JS
A snippet of jsconfig.json file configuration for absolute imports in Next JS

Watch Video

Summary
Review Date
Reviewed Item
How to Import Components using Absolute Imports in Next JS
Author Rating
51star1star1star1star1star
Software Name
Next JS
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development