Absolute imports in Next.js
By Flavio Copes
Learn how to set up absolute imports in Next.js by adding a jsconfig.json file with baseUrl set to the project root, so you can drop those relative paths.
To use absolute imports in Next.js, add a jsconfig.json file in the root of your project and set baseUrl to .. From that moment you can import from the project root instead of climbing up folders with ../.
Wouldn’t it be great if we could avoid relative paths in imports, in our React components in Next.js?
So instead of for example:
import Layout from '../../components/layout'
We could just write:
import Layout from 'components/layout'
This is possible, and it’s called absolute imports.
Why bother?
Relative paths get worse as the project grows. A deeply nested component ends up with imports like ../../../components/layout, and counting dots is not fun.
They’re also fragile. Move a file one folder deeper, and every relative import inside it breaks. Absolute imports always start from the project root, so moving files around doesn’t touch them.
How to set it up
Just add a file named jsconfig.json in the root of your project with this content:
{
"compilerOptions": {
"baseUrl": "."
}
}
That’s it, absolute imports will start working.
If your project uses TypeScript, put the same compilerOptions in your tsconfig.json instead. Next.js reads either file.
One thing to remember: if the dev server is running, restart it. Next.js picks up the configuration on startup, so the new imports fail until you stop and run npm run dev again. That restart is the step I forget most often.
Adding a path alias
You can go one step further and define an alias with the paths option:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
}
Now the import becomes:
import Layout from '@/components/layout'
Why I prefer the alias
With baseUrl alone, import Layout from 'components/layout' looks exactly like an npm package import. If a package named components ever ends up in your node_modules, you have an ambiguity problem, and anyone reading the code can’t tell local files from dependencies at a glance.
The @/ prefix removes all doubt. Anything starting with @/ is your code, everything else comes from node_modules.
Related posts about next: