I'm building my personal website with Next.js and I came across this question after running yarn create next-app --typescript
:
What import alias would you like configured? › @/*
I'm familiar with the concept of import aliases, but I didn't know how Next expected this question to be answered. Usually, I use multiple import aliases. I might use @styles
, @components
, @hooks
, etc.
So I decided to experiment. I typed @components
into the prompt, and I got this response back:
Import alias must follow the pattern <prefix>/*
Got it. So then I tried @components/*
, and my app was created. I checked my tsconfig.json
(or jsconfig.json
) and compared it to an app that used the default @/*
.
// tsconfig.json with default (@/*)
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
...
}
// tsconfig.json with test (@components/*)
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@components/*": ["./*"]
}
},
...
}
What came out of the test is not what I wanted. In the past, I've used a pattern like this:
// tsconfig.json
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"],
"@styles/*": ["styles/*"],
"@hooks/*": ["hooks/*"]
}
},
...
}
Which allowed me to reference imports like this:
import Button from '@components/Button';
Using the default ("@/*": ["./*"]
) provided by the Next.js setup wizard allows me to do the same thing without having to explicitly set each path in my tsconfig.json
— I just need to add an extra /
after the @
to my import path, like so:
import Button from '@/components/Button';
This keeps my tsconfig.json
from getting bloated and hard to maintain (compared to the pattern I used to use). Cool!
The only use case I can think of for modifying this default is if you are using an src/
folder.
Do you have a use case I'm not thinking of? Leave a comment if so!
Top comments (2)
In case, like me, you don't like the look of the extra
/
(or having to change muscle memory to include it whenever tooling doesn't auto-add the import), you can also just modify the default from"@/*": [...]
to"@*": [...]
. This way you can keep writing@components/...
instead of@/components/...
So can I create an import alias after installing a next.js app ? Nice and good piece of work is very helpful, thank you.