Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggest using import.meta.glob #9181

Merged
merged 14 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions src/content/docs/en/guides/imports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -183,16 +183,17 @@ import logoUrl from '@assets/logo.png?url';
These aliases are also integrated automatically into [VS Code](https://code.visualstudio.com/docs/languages/jsconfig) and other editors.


## `Astro.glob()`
## `import.meta.glob()`
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved

[`Astro.glob()`](/en/reference/api-reference/#astroglob) is a way to import many files at once.
[`import.meta.glob()`](https://vitejs.dev/guide/features.html#glob-import) is a way to import many files at once.
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved

`Astro.glob()` only takes one parameter: a relative [glob pattern](/en/guides/imports/#glob-patterns) matching the local files you'd like to import. It’s asynchronous, and returns an array of each matching file's exports.
`import.meta.glob()` only takes one parameter: a relative [glob pattern](/en/guides/imports/#glob-patterns) matching the local files you'd like to import. It’s asynchronous, and returns an array of each matching file's exports.

```astro title="src/components/my-component.astro"
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved
---
// imports all files that end with `.md` in `./src/pages/post/`
const posts = await Astro.glob('../pages/post/*.md');
const matches = await import.meta.glob('../pages/post/*.md', { eager: true });
const posts = Object.values(matches);
---
<!-- Renders an <article> for the first 5 blog posts -->
<div>
Expand All @@ -206,12 +207,12 @@ const posts = await Astro.glob('../pages/post/*.md');
</div>
```

Astro components imported using `Astro.glob` are of type [`AstroInstance`](/en/reference/api-reference/#astro-files). You can render each component instance using its `default` property:
Astro components imported using `import.meta.glob` are of type [`AstroInstance`](/en/reference/api-reference/#astro-files). You can render each component instance using its `default` property:

```astro title="src/pages/component-library.astro" {8}
---
// imports all files that end with `.astro` in `./src/components/`
const components = await Astro.glob('../components/*.astro');
const components = Object.values(await import.meta.glob('../components/*.astro'));
---
<!-- Display all of our components -->
{components.map((component) => (
Expand All @@ -230,7 +231,7 @@ For example, the glob pattern `./pages/**/*.{md,mdx}` starts within the pages su

#### Glob Patterns in Astro

To use with `Astro.glob()`, the glob pattern must be a string literal and cannot contain any variables. See [the troubleshooting guide](/en/guides/troubleshooting/#astroglob---no-matches-found) for a workaround.
To use with `import.meta.glob()`, the glob pattern must be a string literal and cannot contain any variables.

Additionally, glob patterns must begin with one of the following:
- `./` (to start in the current directory)
Expand All @@ -240,9 +241,9 @@ Additionally, glob patterns must begin with one of the following:

[Read more about the glob pattern syntax](https://github.com/mrmlnc/fast-glob#pattern-syntax).

#### `Astro.glob()` vs `getCollection()`
#### `import.meta.glob()` vs `getCollection()`

[Content collections](/en/guides/content-collections/) provide a [`getCollection()` API](/en/reference/api-reference/#getcollection) for loading multiple files instead of `Astro.glob()`. If your content files (e.g. Markdown, MDX, Markdoc) are located in collections within the `src/content/` directory, use `getCollection()` to [query a collection](/en/guides/content-collections/#querying-collections) and return content entries.
[Content collections](/en/guides/content-collections/) provide a [`getCollection()` API](/en/reference/api-reference/#getcollection) for loading multiple files instead of `import.meta.glob()`. If your content files (e.g. Markdown, MDX, Markdoc) are located in collections within the `src/content/` directory, use `getCollection()` to [query a collection](/en/guides/content-collections/#querying-collections) and return content entries.
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved

## WASM

Expand Down
36 changes: 11 additions & 25 deletions src/content/docs/en/guides/markdown-content.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,16 @@ Visit the [MDX website](https://mdxjs.com/table-of-components/) for a full list

You can import Markdown and MDX files directly into your Astro files. This gives you access to their Markdown content, as well as other properties such as frontmatter values that can be used within Astro's JSX-like expressions.

You can import one specific page with an `import` statement, or multiple pages with [`Astro.glob()`](/en/guides/imports/#astroglob).
You can import one specific page with an `import` statement, or multiple pages with [`import.meta.glob()`](https://vitejs.dev/guide/features.html#glob-import).
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved

```astro title="src/pages/index.astro"
---
// Import a single file
import * as myPost from '../pages/post/my-post.md';

// Import multiple files with Astro.glob
const posts = await Astro.glob('../pages/post/*.md');
// Import multiple files with import.meta.glob
const matches = await import.meta.glob('../pages/post/*.md', { eager: true });
const posts = Object.values(posts);
---
```

Expand All @@ -238,7 +239,7 @@ Here is my _great_ post!
---
import * as greatPost from '../pages/post/great-post.md';

const posts = await Astro.glob('../pages/post/*.md');
const posts = Object.values(await import.meta.glob('../pages/post/*.md', { eager: true }));
---

<p>{greatPost.frontmatter.title}</p>
Expand Down Expand Up @@ -272,30 +273,13 @@ import * as greatPost from '../pages/post/mdx-post.mdx';
<p>{greatPost.description}</p>
```

You can optionally provide a type for the `frontmatter` variable using a TypeScript generic:

```astro title="src/pages/index.astro" ins={2-5} ins="<Frontmatter>"
---
interface Frontmatter {
title: string;
description?: string;
}
const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');
---

<ul>
{posts.map(post => <li>{post.frontmatter.title}</li>)}
<!-- post.frontmatter.title will be `string`! -->
</ul>
```

### Exported Properties

:::note[Using an Astro layout?]
See the [properties exported to an Astro layout component](/en/basics/layouts/#markdown-layout-props) when using Astro's special [frontmatter layout](#frontmatter-layout).
:::

The following properties are available to a `.astro` component when using an `import` statement or `Astro.glob()`:
The following properties are available to a `.astro` component when using an `import` statement or `import.meta.glob()`:

- **`file`** - The absolute file path (e.g. `/home/user/projects/.../file.md`).
- **`url`** - If it's a page, the URL of the page (e.g. `/en/guides/markdown-content`).
Expand Down Expand Up @@ -329,7 +313,8 @@ To access your Markdown content, pass the `<Content/>` component through the Ast
```astro title="src/pages/[slug].astro" {9-11} "Content" "Astro.props.post"
---
export async function getStaticPaths() {
const posts = await Astro.glob('../posts/**/*.md')
const matches = await import.meta.glob('../posts/**/*.md', { eager: true })
const posts = Object.values(matches);

return posts.map(post => ({
params: {
Expand Down Expand Up @@ -359,12 +344,13 @@ For example, you can export a `title` field from an MDX page or component.
export const title = 'My first MDX post'
```

This `title` will be accessible from `import` and [Astro.glob()](/en/reference/api-reference/#astroglob) statements:
This `title` will be accessible from `import` and [import.meta.glob()](https://vitejs.dev/guide/features.html#glob-import) statements:
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved

```astro
---
// src/pages/index.astro
const posts = await Astro.glob('./*.mdx');
const matches = await import.meta.glob('./*.mdx', { eager: true });
const posts = Object.values(posts);
---

{posts.map(post => <p>{post.title}</p>)}
Expand Down
8 changes: 4 additions & 4 deletions src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ Here are some tips for converting a Next `.js` component into a `.astro` compone

5. Decide whether any imported components also need to be converted to Astro. With the official integration installed, you can [use existing React components in your Astro file](/en/guides/framework-components/). But, you may want to convert them to `.astro` components, especially if they do not need to be interactive!

6. Replace `getStaticProps()` with import statements or [`Astro.glob()`](/en/reference/api-reference/#astroglob) to query your local files. Use `fetch()` to fetch external data.
6. Replace `getStaticProps()` with import statements or [`import.meta.glob()`](https://vitejs.dev/guide/features.html#glob-import) to query your local files. Use `fetch()` to fetch external data.
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved

See [an example of a Next `.js` file converted step-by-step](#guided-example-next-data-fetching-to-astro).

Expand Down Expand Up @@ -383,7 +383,7 @@ See more about [specific `<slot />` usage in Astro](/en/basics/astro-components/

### Next Data Fetching to Astro

Convert any instances of `getStaticProps()` to either `Astro.glob()` or `getCollection()`/`getEntryBySlug()` in order to access data from other files in your project source. To [fetch remote data](/en/guides/data-fetching/), use `fetch()`.
Convert any instances of `getStaticProps()` to either `import.meta.glob()` or `getCollection()`/`getEntryBySlug()` in order to access data from other files in your project source. To [fetch remote data](/en/guides/data-fetching/), use `fetch()`.

These data requests are made in the frontmatter of the Astro component and use top-level await.

Expand All @@ -395,15 +395,15 @@ import { getCollection } from 'astro:content';
const allBlogPosts = await getCollection('blog');

// Get all `src/pages/posts/` entries
const allPosts = await Astro.glob('../pages/posts/*.md');
const allPosts = Object.values(await import.meta.glob('../pages/posts/*.md', { eager: true }));

const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
const randomUser = data.results[0];
---
```

See more about [local files imports with `Astro.glob()`](/en/guides/imports/#astroglob), [querying using the Collections API](/en/guides/content-collections/#querying-collections) or [fetching remote data](/en/guides/data-fetching/).
See more about [local files imports with `import.meta.glob()`](https://vitejs.dev/guide/features.html#glob-import), [querying using the Collections API](/en/guides/content-collections/#querying-collections) or [fetching remote data](/en/guides/data-fetching/).

### Next Styling to Astro

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/en/guides/routing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ In the following example, we will implement nested pagination to build the URLs
// src/pages/[tag]/[page].astro
export async function getStaticPaths({ paginate }) {
const allTags = ['red', 'blue', 'green'];
const allPosts = await Astro.glob('../../posts/*.md');
const allPosts = Object.values(await import.meta.glob('../pages/post/*.md', { eager: true }));
// For every tag, return a paginate() result.
// Make sure that you pass `{params: {tag}}` to `paginate()`
// so that Astro knows which tag grouping the result is for.
Expand Down
4 changes: 4 additions & 0 deletions src/content/docs/en/reference/api-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ The `Astro` global is available in all contexts in `.astro` files. It has the fo

### `Astro.glob()`

:::caution[Deprecated]
Use [`import.meta.glob`](https://vitejs.dev/guide/features.html#glob-import) to query project files. Usage of `Astro.glob` can be replaced with `Object.values(await import.meta.glob('../pages/post/*.md', { eager: true }));`.
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved
:::

`Astro.glob()` is a way to load many local files into your static site setup.

```astro
Expand Down
20 changes: 10 additions & 10 deletions src/content/docs/en/tutorial/5-astro-api/1.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,20 @@ import { Steps } from '@astrojs/starlight/components';
Now that you have a few blog posts to link to, it's time to configure the Blog page to create a list of them automatically!

<PreCheck>
- Access data from all your posts at once using `Astro.glob()`
- Access data from all your posts at once using `import.meta.glob()`
- Display a dynamically generated list of posts on your Blog page
- Refactor to use a `<BlogPost />` component for each list item
</PreCheck>

## Dynamically display a list of posts

<Steps>
1. Add the following code to `blog.astro` to return information about all your Markdown files. `Astro.glob()` will return an array of objects, one for each blog post.
1. Add the following code to `blog.astro` to return information about all your Markdown files. `import.meta.glob()` will return an array of objects, one for each blog post.

```astro title="src/pages/blog.astro" ins={3}
---
import BaseLayout from '../layouts/BaseLayout.astro'
const allPosts = await Astro.glob('./posts/*.md');
const allPosts = Object.values(await import.meta.glob('./posts/*.md', { eager: true }));
const pageTitle = "My Astro Learning Blog";
---
<BaseLayout pageTitle={pageTitle}>
Expand All @@ -48,7 +48,7 @@ Now that you have a few blog posts to link to, it's time to configure the Blog p
```astro title="src/pages/blog.astro" del={9,10,11} ins={13}
---
import BaseLayout from '../layouts/BaseLayout.astro'
const allPosts = await Astro.glob('./posts/*.md');
const allPosts = await Object.values(import.meta.glob('./posts/*.md', { eager: true }));
const pageTitle = "My Astro Learning Blog";
---
<BaseLayout pageTitle={pageTitle}>
Expand All @@ -63,7 +63,7 @@ Now that you have a few blog posts to link to, it's time to configure the Blog p
</BaseLayout>
```

Your entire list of blog posts is now being generated dynamically, by mapping over the array returned by `Astro.glob()`.
Your entire list of blog posts is now being generated dynamically, by mapping over the array returned by `import.meta.glob()`.

3. Add a new blog post by creating a new `post-4.md` file in `src/pages/posts/` and adding some Markdown content. Be sure to include at least the frontmatter properties used below.

Expand All @@ -79,7 +79,7 @@ Now that you have a few blog posts to link to, it's time to configure the Blog p
pubDate: 2022-08-08
tags: ["astro", "successes"]
---
This post should show up with my other blog posts, because `Astro.glob()` is returning a list of all my posts in order to create my list.
This post should show up with my other blog posts, because `import.meta.glob()` is returning a list of all my posts in order to create my list.
```

4. Revisit your blog page in your browser preview at `http://localhost:4321/blog` and look for an updated list with four items, including your new blog post!
Expand Down Expand Up @@ -141,7 +141,7 @@ Try on your own to make all the necessary changes to your Astro project so that
---
import BaseLayout from '../layouts/BaseLayout.astro';
import BlogPost from '../components/BlogPost.astro';
const allPosts = await Astro.glob('../pages/posts/*.md');
const allPosts = Object.values(await import.meta.glob('../pages/posts/*.md', { eager: true }));
const pageTitle = "My Astro Learning Blog";
---
```
Expand All @@ -161,7 +161,7 @@ Try on your own to make all the necessary changes to your Astro project so that
---
import BaseLayout from '../layouts/BaseLayout.astro';
import BlogPost from '../components/BlogPost.astro';
const allPosts = await Astro.glob('../pages/posts/*.md');
const allPosts = Object.values(await import.meta.glob('../pages/posts/*.md', { eager: true }));
const pageTitle = "My Astro Learning Blog"
---
<BaseLayout pageTitle={pageTitle}>
Expand All @@ -186,7 +186,7 @@ If your Astro component contains the following line of code:

```astro
---
const myPosts = await Astro.glob('./posts/*.md');
const myPosts = Object.values(await import.meta.glob('./posts/*.md', { eager: true }));
---
```

Expand Down Expand Up @@ -248,4 +248,4 @@ Choose the syntax you could write to represent:

### Resources

- [`Astro.glob()` API documentation](/en/reference/api-reference/#astroglob)
- [`Glob import API documentation](https://vitejs.dev/guide/features.html#glob-import)
sarah11918 marked this conversation as resolved.
Show resolved Hide resolved
8 changes: 4 additions & 4 deletions src/content/docs/en/tutorial/5-astro-api/2.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ You can create entire sets of pages dynamically using `.astro` files that export
import BaseLayout from '../../layouts/BaseLayout.astro';

export async function getStaticPaths() {
const allPosts = await Astro.glob('../posts/*.md');
const allPosts = Object.values(await import.meta.glob('../posts/*.md', { eager: true }));

return [
{params: {tag: "astro"}, props: {posts: allPosts}},
Expand Down Expand Up @@ -129,7 +129,7 @@ You can create entire sets of pages dynamically using `.astro` files that export

For each of the following, state whether the code is written **inside** the `getStaticPaths()` function, or **outside** of it.

1. The `Astro.glob()` call to receive information about all your `.md` files to pass to each page route.
1. The `import.meta.glob()` call to receive information about all your `.md` files to pass to each page route.

<MultipleChoice>
<Option isCorrect>inside `getStaticPaths`</Option>
Expand Down Expand Up @@ -183,7 +183,7 @@ Even if it looks challenging, you can try following along with the steps to buil
import BaseLayout from '../../layouts/BaseLayout.astro';

export async function getStaticPaths() {
const allPosts = await Astro.glob('../posts/*.md');
const allPosts = Object.values(await import.meta.glob('../posts/*.md', { eager: true }));

const uniqueTags = [...new Set(allPosts.map((post) => post.frontmatter.tags).flat())];
}
Expand Down Expand Up @@ -249,7 +249,7 @@ import BaseLayout from '../../layouts/BaseLayout.astro';
import BlogPost from '../../components/BlogPost.astro';

export async function getStaticPaths() {
const allPosts = await Astro.glob('../posts/*.md');
const allPosts = Object.values(await import.meta.glob('../posts/*.md', { eager: true }));

const uniqueTags = [...new Set(allPosts.map((post) => post.frontmatter.tags).flat())];

Expand Down
6 changes: 3 additions & 3 deletions src/content/docs/en/tutorial/5-astro-api/3.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ Fortunately, you already know a way to grab the data from all your Markdown file
```astro title = "src/pages/tags/index.astro" ins={3}
---
import BaseLayout from '../../layouts/BaseLayout.astro';
const allPosts = await Astro.glob('../posts/*.md');
const allPosts = Object.values(await import.meta.glob('../posts/*.md', { eager: true }));
const pageTitle = "Tag Index";
---
```
Expand All @@ -125,7 +125,7 @@ Fortunately, you already know a way to grab the data from all your Markdown file
```astro title = "src/pages/tags/index.astro" ins={4}
---
import BaseLayout from '../../layouts/BaseLayout.astro';
const allPosts = await Astro.glob('../posts/*.md');
const allPosts = Object.values(await import.meta.glob('../posts/*.md', { eager: true }));
const tags = [...new Set(allPosts.map((post) => post.frontmatter.tags).flat())];
const pageTitle = "Tag Index";
---
Expand Down Expand Up @@ -209,7 +209,7 @@ Here is what your new page should look like:
```astro title="src/pages/tags/index.astro"
---
import BaseLayout from '../../layouts/BaseLayout.astro';
const allPosts = await Astro.glob('../posts/*.md');
const allPosts = Object.values(await Astro.glob('../posts/*.md', { eager: true }));
const tags = [...new Set(allPosts.map((post) => post.frontmatter.tags).flat())];
const pageTitle = "Tag Index";
---
Expand Down
Loading
Loading