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:
- Create an
jsconfig.json
in the root of your project. - 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 importingimport Cart from '../../carts/cart'
will change toimport 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. - After Changes Restart the server using
npm run dev

A snippet of jsconfig.json file configuration for absolute imports in Next JS
Watch Video
Summary
Reviewer
TheCodeLearner
Review Date
Reviewed Item
How to Import Components using Absolute Imports in Next JS
Author Rating





Software Name
Next JS
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development