Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
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
26 changes: 26 additions & 0 deletions .changeset/kind-pears-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'astro': major
---

Removes `Astro.glob()`

In Astro 5.0, `Astro.glob()` was deprecated in favor of using `getCollection()` to query your collections, and `import.meta.glob()` to query other source files in your project.

Astro 6.0 removes `Astro.glob()` entirely. Update to `import.meta.glob()` to keep your current behavior.

#### What should I do?

Replace all use of `Astro.glob()` with `import.meta.glob()`. Note that `import.meta.glob()` no longer returns a `Promise`, so you may have to update your code accordingly. You should not require any updates to your glob patterns.

```astro
---
// src/pages/blog.astro
-const posts = await Astro.glob('./posts/*.md');
+const posts = Object.values(import.meta.glob('./posts/*.md', { eager: true }));
---
{posts.map((post) => <li><a href={post.url}>{post.frontmatter.title}</a></li>)}
```

Where appropriate, consider using content collections to organize your content, which has its own newer, more performant querying functions.

You may also wish to consider using glob packages from NPM, such as `fast-glob`.
12 changes: 0 additions & 12 deletions packages/astro/e2e/errors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,18 +117,6 @@ test.describe('Error display', () => {
expect(await page.locator('vite-error-overlay').count()).toEqual(0);
});

test('astro glob no match error', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/astro-glob-no-match'), { waitUntil: 'networkidle' });
const message = (await getErrorOverlayContent(page)).message;
expect(message).toMatch('did not return any matching files');
});

test('astro glob used outside of an astro file', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/astro-glob-outside-astro'), { waitUntil: 'networkidle' });
const message = (await getErrorOverlayContent(page)).message;
expect(message).toMatch('can only be used in');
});

test('can handle DomException errors', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/dom-exception'), { waitUntil: 'networkidle' });
const message = (await getErrorOverlayContent(page)).message;
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

2 changes: 0 additions & 2 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@
"@capsizecss/unpack": "^2.4.0",
"@oslojs/encoding": "^1.1.0",
"@rollup/pluginutils": "^5.2.0",
"acorn": "^8.15.0",
"aria-query": "^5.3.2",
"axobject-query": "^4.1.0",
"boxen": "8.0.1",
Expand All @@ -130,7 +129,6 @@
"dset": "^3.1.4",
"es-module-lexer": "^1.7.0",
"esbuild": "^0.25.0",
"estree-walker": "^3.0.3",
"flattie": "^1.1.1",
"fontace": "~0.3.0",
"github-slugger": "^2.0.0",
Expand Down
2 changes: 0 additions & 2 deletions packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import astroDevToolbar from '../toolbar/vite-plugin-dev-toolbar.js';
import astroTransitions from '../transitions/vite-plugin-transitions.js';
import type { AstroSettings, RoutesList } from '../types/astro.js';
import astroVitePlugin from '../vite-plugin-astro/index.js';
import astroPostprocessVitePlugin from '../vite-plugin-astro-postprocess/index.js';
import { vitePluginAstroServer } from '../vite-plugin-astro-server/index.js';
import configAliasVitePlugin from '../vite-plugin-config-alias/index.js';
import vitePluginFileURL from '../vite-plugin-fileurl/index.js';
Expand Down Expand Up @@ -158,7 +157,6 @@ export async function createVite(
astroEnv({ settings, sync, envLoader }),
markdownVitePlugin({ settings, logger }),
htmlVitePlugin(),
astroPostprocessVitePlugin(),
astroIntegrationsContainerPlugin({ settings, logger }),
astroScriptsPageSSRPlugin({ settings }),
astroHeadPlugin(),
Expand Down
25 changes: 1 addition & 24 deletions packages/astro/src/core/errors/dev/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ErrorPayload } from 'vite';
import type { SSRLoadedRenderer } from '../../../types/public/internal.js';
import type { ModuleLoader } from '../../module-loader/index.js';
import { AstroError, type ErrorWithMetadata } from '../errors.js';
import { FailedToLoadModuleSSR, InvalidGlob, MdxIntegrationMissingError } from '../errors-data.js';
import { FailedToLoadModuleSSR, MdxIntegrationMissingError } from '../errors-data.js';
import { createSafeError } from '../utils.js';
import { getDocsForError, renderErrorMarkdown } from './utils.js';

Expand Down Expand Up @@ -76,29 +76,6 @@ export function enhanceViteSSRError({
stack: safeError.stack,
}) as ErrorWithMetadata;
}

// Since Astro.glob is a wrapper around Vite's import.meta.glob, errors don't show accurate information, let's fix that
if (safeError.message.includes('Invalid glob')) {
const globPattern = /glob: "(.+)" \(/.exec(safeError.message)?.[1];

if (globPattern) {
safeError.message = InvalidGlob.message(globPattern);
safeError.name = 'InvalidGlob';
safeError.title = InvalidGlob.title;

const line = lns.findIndex((ln) => ln.includes(globPattern));

if (line !== -1) {
const column = lns[line]?.indexOf(globPattern);

safeError.loc = {
file: path,
line: line + 1,
column,
};
}
}
}
}

return safeError;
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/core/errors/errors-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,7 @@ export const LocalImageUsedWrongly = {
* - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob)
* @description
* `Astro.glob()` can only be used in `.astro` files. You can use [`import.meta.glob()`](https://vite.dev/guide/features.html#glob-import) instead to achieve the same result.
* @deprecated Removed in Astro v6.0.0 as it is no longer relevant due to the removal of `Astro.glob()`.
*/
export const AstroGlobUsedOutside = {
name: 'AstroGlobUsedOutside',
Expand All @@ -966,6 +967,7 @@ export const AstroGlobUsedOutside = {
* - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob)
* @description
* `Astro.glob()` did not return any matching files. There might be a typo in the glob pattern.
* @deprecated Removed in Astro v6.0.0 as it is no longer relevant due to the removal of `Astro.glob()`.
*/
export const AstroGlobNoMatch = {
name: 'AstroGlobNoMatch',
Expand Down Expand Up @@ -1075,6 +1077,7 @@ export const FailedToLoadModuleSSR = {
* - [Glob Patterns](https://docs.astro.build/en/guides/imports/#glob-patterns)
* @description
* Astro encountered an invalid glob pattern. This is often caused by the glob pattern not being a valid file path.
* @deprecated Removed in Astro v6.0.0 as it is no longer relevant due to the removal of `Astro.glob()`.
*/
export const InvalidGlob = {
name: 'InvalidGlob',
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/core/render-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,6 @@ export class RenderContext {

return {
generator: astroStaticPartial.generator,
glob: astroStaticPartial.glob,
routePattern: this.routeData.route,
isPrerendered: this.routeData.prerender,
cookies,
Expand Down
30 changes: 0 additions & 30 deletions packages/astro/src/runtime/server/astro-global.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,11 @@
import { ASTRO_VERSION } from '../../core/constants.js';
import { AstroError, AstroErrorData } from '../../core/errors/index.js';
import type { AstroGlobalPartial } from '../../types/public/context.js';

/** Create the Astro.glob() runtime function. */
function createAstroGlobFn() {
const globHandler = (importMetaGlobResult: Record<string, any>) => {
// This is created inside of the runtime so we don't have access to the Astro logger.
console.warn(`Astro.glob is deprecated and will be removed in a future major version of Astro.
Use import.meta.glob instead: https://vitejs.dev/guide/features.html#glob-import`);

if (typeof importMetaGlobResult === 'string') {
throw new AstroError({
...AstroErrorData.AstroGlobUsedOutside,
message: AstroErrorData.AstroGlobUsedOutside.message(JSON.stringify(importMetaGlobResult)),
});
}
let allEntries = [...Object.values(importMetaGlobResult)];
if (allEntries.length === 0) {
throw new AstroError({
...AstroErrorData.AstroGlobNoMatch,
message: AstroErrorData.AstroGlobNoMatch.message(JSON.stringify(importMetaGlobResult)),
});
}
// Map over the `import()` promises, calling to load them.
return Promise.all(allEntries.map((fn) => fn()));
};
// Cast the return type because the argument that the user sees (string) is different from the argument
// that the runtime sees post-compiler (Record<string, Module>).
return globHandler as unknown as AstroGlobalPartial['glob'];
}

// This is used to create the top-level Astro global; the one that you can use
// inside of getStaticPaths. See the `astroGlobalArgs` option for parameter type.
export function createAstro(site: string | undefined): AstroGlobalPartial {
return {
site: site ? new URL(site) : undefined,
generator: `Astro v${ASTRO_VERSION}`,
glob: createAstroGlobFn(),
};
}
22 changes: 0 additions & 22 deletions packages/astro/src/types/public/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import type {
ActionClient,
ActionReturnType,
} from '../../actions/runtime/virtual/server.js';
import type { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from '../../core/constants.js';
import type { AstroCookies } from '../../core/cookies/cookies.js';
import type { CspDirective, CspHash } from '../../core/csp/config.js';
import type { AstroSession } from '../../core/session.js';
import type { AstroComponentFactory } from '../../runtime/server/index.js';
import type { Params, RewritePayload } from './common.js';
import type { ValidRedirectStatus } from './config.js';
import type { AstroInstance, MarkdownInstance, MDXInstance } from './content.js';

/**
* Astro global available in all contexts in .astro files
Expand Down Expand Up @@ -208,27 +206,7 @@ export interface AstroGlobal<
};
}

/** Union type of supported markdown file extensions */
type MarkdownFileExtension = (typeof SUPPORTED_MARKDOWN_FILE_EXTENSIONS)[number];

export interface AstroGlobalPartial {
/**
* Fetch local files into your static site setup
*
* Example usage:
* ```typescript
* const posts = await Astro.glob('../pages/post/*.md');
* ```
*
* [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroglob)
* @deprecated Astro.glob is deprecated and will be removed in the next major version of Astro. Use `import.meta.glob` instead: https://vitejs.dev/guide/features.html#glob-import
*/
glob(globStr: `${any}.astro`): Promise<AstroInstance[]>;
glob<T extends Record<string, any>>(
globStr: `${any}${MarkdownFileExtension}`,
): Promise<MarkdownInstance<T>[]>;
glob<T extends Record<string, any>>(globStr: `${any}.mdx`): Promise<MDXInstance<T>[]>;
glob<T extends Record<string, any>>(globStr: string): Promise<T[]>;
/**
* Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option
*
Expand Down
3 changes: 0 additions & 3 deletions packages/astro/src/vite-plugin-astro-postprocess/README.md

This file was deleted.

65 changes: 0 additions & 65 deletions packages/astro/src/vite-plugin-astro-postprocess/index.ts

This file was deleted.

6 changes: 3 additions & 3 deletions packages/astro/test/astro-global.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('Astro Global', () => {
assert.equal($('#nested-child-pathname').text(), '/blog/');
});

it('Astro.glob() returned `url` metadata of each markdown file extensions DOES NOT include the extension', async () => {
it('import.meta.glob() returned `url` metadata of each markdown file extensions DOES NOT include the extension', async () => {
const html = await fixture.fetch('/blog/omit-markdown-extensions/').then((res) => res.text());
const $ = cheerio.load(html);
assert.equal(
Expand Down Expand Up @@ -90,13 +90,13 @@ describe('Astro Global', () => {
assert.equal($('#site').attr('href'), 'https://mysite.dev/subsite/');
});

it('Astro.glob() correctly returns an array of all posts', async () => {
it('import.meta.glob() correctly returns an array of all posts', async () => {
const html = await fixture.readFile('/posts/1/index.html');
const $ = cheerio.load(html);
assert.equal($('.post-url').attr('href'), '/blog/post/post-2');
});

it('Astro.glob() correctly returns meta info for MD and Astro files', async () => {
it('import.meta.glob() correctly returns meta info for MD and Astro files', async () => {
const html = await fixture.readFile('/glob/index.html');
const $ = cheerio.load(html);
assert.equal($('[data-file]').length, 8);
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/test/astro-scripts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ describe('Scripts', () => {
assert.equal(entryURL.includes('_astro/'), true);
});

it('Scripts added via Astro.glob are hoisted', async () => {
it('Scripts added via import.meta.glob are hoisted', async () => {
let glob = await fixture.readFile('/glob/index.html');
let $ = cheerio.load(glob);

Expand Down Expand Up @@ -131,7 +131,7 @@ describe('Scripts', () => {
await devServer.stop();
});

it('Scripts added via Astro.glob are hoisted', async () => {
it('Scripts added via import.meta.glob are hoisted', async () => {
let res = await fixture.fetch('/glob');
let html = await res.text();
let $ = cheerio.load(html);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
const data = await Astro.glob('./post/**/*');
const data = Object.values(import.meta.glob('./post/**/*', { eager: true }));
---

<html>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
import Route from "../components/Route.astro";

const markdownPosts = await Astro.glob('./post/**/*.{markdown,mdown,mkdn,mkd,mdwn,md}');
const markdownPosts = Object.values(import.meta.glob('./post/**/*.{markdown,mdown,mkdn,mkd,mdwn,md}', { eager: true }));
const markdownExtensions = /(\.(markdown|mdown|mkdn|mkd|mdwn|md))$/g
const aUrlContainsExtension = markdownPosts.some((page:any)=> {
return markdownExtensions.test(page.url)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import Route from "../../components/Route.astro";

export async function getStaticPaths({paginate}) {
const data = await Astro.glob('../post/*.md');
const data = Object.values(import.meta.glob('../post/*.md', { eager: true }));
return paginate(data, {pageSize: 1});
}
const { page } = Astro.props;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
export async function getStaticPaths({paginate}) {
const allPosts = await Astro.glob('../../post/*.md');
const allPosts = Object.values(import.meta.glob('../../post/*.md', { eager: true }));
return ['red', 'blue'].flatMap((filter) => {
const filteredPosts = allPosts.filter((post) => post.frontmatter.tag === filter);
return paginate(filteredPosts, {
Expand Down
Loading