NextJS Typescript Import Alias

NextJSTypescriptImportAliasesJavascript
Code snippet

This one is straightforward!

You probably saw in one or two projects, aliases on typescript import statements, just like this:

import { Header } from '@components/Header'

So how can we achieve this kind of import on a NextJS project?

Basic setup:

npx create-next-app@latest

These are my configs:

npx create nextjs config

The latest versions of NextJS will have the @ as the src/*, and you can check this inside the tsconfig.json file on the paths property:

...
"paths": {
"@/*": ["./src/*"]
}
...

You definitely saw the answer here, right?

To create a @component alias you need to add:

"paths": {
"@/*": ["./src/*"],
"@components": ["./src/components/*"]
}

I can show you an example of how to use it.

Let's assume that we have a Header.tsx inside the src/components:

list files

And inside the page.tsx we can:

import {button} from '@components'

That is it!

Pretty easy right?

Thank you so much and I am looking forward to seeing you soon. 😉

And if you like content about Git, Linux, Productivity tips, Typescript, and Python please follow me Marco Antonio Bet, and pay me a coffee.

Going further

To learn more:

Full project on GitHub repository.

Share?