Absolute imports in Next.js
Cleaning relative imports
If you've ever imported modules in a JavaScript or TypeScript project, you've probably seen something like this:
import { Layout } from '../../layout/Layout'
import { fetchFromGraphCMS } from '../../../lib/graphcms'
import { WORK_SLUGS_QUERY, SINGLE_WORK_PAGE_QUERY } from '../../../lib/queries'
The path of the imported modules is relative to the location of the current file.
I recently discovered an alternative way. Take a look at this:
import { Layout } from '@/layout/Layout'
import { fetchFromGraphCMS } from '@/lib/graphcms'
import { WORK_SLUGS_QUERY, SINGLE_WORK_PAGE_QUERY } from '@/lib/queries'
See those @
signs? They refer to an absolute path that conveniently can be configured in Next.js. This is how the configuration looks in my tsconfig.json
file:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@/*": ["*"]
}
},
}
The baseUrl
defines what folder should be considered the root we refer to in our imports. In my case that's a src
folder in the root of the project. The paths
object defines an alias to that baseUrl
. I've used @
as a convention to tell my imports apart from package imports.
One upside of absolute imports is that the path will stay the same when you move the statement between files.
Now you're ready to enjoy your new, clean path structures. Enjoy!
Get in touch
I'm not currently looking for freelancer work, but if you want to have a chat, feel free to contact me.