docs
docs copied to clipboard
Subpath imports
📚 Subject area/topic
Imports
📋 Suggested page
https://docs.astro.build/en/guides/aliases/
📋 General description or bullet points (if proposing new content)
There is native way to have import aliases: https://stackoverflow.com/questions/70158055/how-to-have-aliases-with-nodejs-import. It work in astro development server and production.
It should be documented and preferred approach instead of astro specific import aliases in tsconfig.json.
🖥️ Reproduction of code samples in StackBlitz
No response
For additional context, this method used to not work in the editor before Astro 3 because we were stuck on moduleResolution: 'node', that's why it was documented to use the tsconfig.json method instead, which worked in all contexts (Vite/Node, TypeScript, the editor etc)
Nowadays, if this method does actually work (I'd make sure it works in all contexts, since it mostly depends on Vite supporting it and not really Node), I'd be in favour of documenting it, it's okay
I was about to add create a ticket myself to recommend changing the current alias examples as they might not work consistently, from
"@components/*": ["src/components/*"],
"@assets/*": ["src/assets/*"]
to
"@/components/*": ["src/components/*"],
"@/assets/*": ["src/assets/*"]
as it seems that any alias with that pattern may conflict with scoped packages and not always resolve correctly.
In particular, if you try to add an alias for types such as:
"@types/*": ["src/types/*"]
And then try to import it:
import type { Example } from "@types/Example";
This will result in the following error:
Cannot import type declaration files. Consider importing 'Example' instead of '@types/Example'.ts(6137)
So simply appending a / after the @ in the alias would resolve this. Otherwise we could consider changing the @ prefix to something else, e.g. # or ~. If the native subpath imports approach is preferred, then great - even better.
Just catching up on this conversation, and it looks like @rekateka 's solution would help avoid errors with our examples!
I would be happy to receive a PR to update the import examples on the Aliases page, and will make sure that @Princesseuh reviews the PR to approve.
@rekateka your comment is not related to this issue you should create another issue.