#Can you use the Astro module in JS files
8 messages · Page 1 of 1 (latest)
Hi @worn cape. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
It seems like you're trying to use the Astro.glob() function in a regular JavaScript file. Unfortunately, you can't use the Astro module in regular JavaScript files. You should use Astro.glob() in the frontmatter of an Astro component instead.
Here's an example of how to use Astro.glob() in an Astro component:
---
const allPosts = await Astro.glob('../pages/posts/*.md');
const tags = [...new Set(allPosts.map((post) => post.frontmatter.tags).flat())];
---
For more information on importing files in Astro, you can refer to the Astro Imports Guide (https://docs.astro.build/en/guides/imports).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@worn cape kapa.ai is still learning and improving, please let us how it did by reacting below
For glob import see https://vitejs.dev/guide/features.html#glob-import
@barren locust but it's possible to reproduce the same for Astro.glob in .js files with the Vite glob import.
Let me check the knowledge base for you. One moment! :books:
Yes, you can achieve similar functionality to Astro.glob() in regular JavaScript files using Vite's import.meta.glob() feature. Here's an example of how to use import.meta.glob() in a JavaScript file:
export default async function getUniqueTags() {
const importGlob = import.meta.glob("../pages/posts/*.md");
const allPosts = await Promise.all(Object.values(importGlob).map((importFn) => importFn()));
const tags = [
...new Set(allPosts.map((post) => post.default.frontmatter.tags).flat()),
];
return tags;
}