docs icon indicating copy to clipboard operation
docs copied to clipboard

Subpath imports

Open cdtut opened this issue 1 year ago • 4 comments
trafficstars

📚 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

cdtut avatar Jan 28 '24 05:01 cdtut

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

Princesseuh avatar Jan 31 '24 07:01 Princesseuh

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.

rekateka avatar Feb 01 '24 12:02 rekateka

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.

sarah11918 avatar Mar 04 '24 15:03 sarah11918

@rekateka your comment is not related to this issue you should create another issue.

cdtut avatar Mar 11 '24 17:03 cdtut