#Dynamic Imports?
3 messages · Page 1 of 1 (latest)
Hi @gentle crystal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro does not support dynamic variables and string interpolation in imports due to a limitation of Vite’s import.meta.glob() function, which only supports static string literals. This is not a bug in Astro.
A common workaround is to import a larger set of files that includes all the files you need using Astro.glob(), then filter them. Here's an example:
---
const { postSlug } = Astro.props;
const pathToMyFeaturedPost = `src/pages/blog/${postSlug}.md`;
const posts = await Astro.glob('../pages/blog/*.md');
const myFeaturedPost = posts.find(post => post.file.includes(pathToMyFeaturedPost));
---
<p> Take a look at my favorite post, <a href={myFeaturedPost.url}>{myFeaturedPost.frontmatter.title}</a>!</p>
In this example, all markdown files in the ../pages/blog/ directory are imported, and then the specific post is found by filtering the imported files.