@ directive in react

I have seen some using this way to import components in his file. @/components/component Can anyone tell me how he is doing this: @/components
8 Replies
clevermissfox
clevermissfox12mo ago
Maybe they’re using Angular JS framework
Nicho
Nicho12mo ago
I have seen this commonly used in Next. When you are trying to import something NextJS automatically does that for you as long as you did default export
Joao
Joao12mo ago
You can configure whatever bundler you're using eg., webpack, vite, etc. to use relative imports. For example in vite you'd have something like:
import { defineConfig } from "vite";

export default defineConfig({
resolve: {
alias: {
"@": "/src",
},
}
});
import { defineConfig } from "vite";

export default defineConfig({
resolve: {
alias: {
"@": "/src",
},
}
});
So that you can use the syntax you mentioned, whereby "@" will be replaced with "/src" in this case. You can take things further and create multiple aliases for different locations to make this even shorter if you'd prefer:
export default defineConfig({
resolve: {
alias: {
"@": "/src",
"@components": "/src/components",
"@hooks": "/src/hooks",
},
}
});
export default defineConfig({
resolve: {
alias: {
"@": "/src",
"@components": "/src/components",
"@hooks": "/src/hooks",
},
}
});
But I'm not sure is really worth it.
Jochem
Jochem12mo ago
You'd still be writing import Something from "@components"; with that though, not just a bare @components
Joao
Joao12mo ago
I haven't looked into Next.js yet... I'm surprised you don't even need to specify the import part of the statement But I'm not really sure how I feel about that, I typically like be explicit about what's included and used in each file
Hammad Hamdani
Hammad HamdaniOP12mo ago
Thanks Joao. I was helpful and this is thumbup
Joao
Joao12mo ago
Just to be clear it seems that Next.js does it a little different though I've never used it, and you can simply import files with @component but I think it's good to be explicit. At least this will help with other projects that are not Next.js specifically.
Hammad Hamdani
Hammad HamdaniOP12mo ago
Thanks.
Want results from more Discord servers?
Add your server