#Dynamic Imports?

3 messages · Page 1 of 1 (latest)

gentle crystal
#
const logoPath = pathArray[2] || './somePath/DefaultLogo.astro'
import Logo from logoPath(); 

Results in:

-!- Expected string but found "logoPath"

Is this avoidable?

marble vigilBOT
#

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.

For more information, you can refer to the Astro documentation on troubleshooting (https://docs.astro.build/en/guides/troubleshooting/#astroglob---no-matches-found).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: