Add error message if Astro.glob is called outside (#7204)

This commit is contained in:
Bjorn Lu 2023-05-26 16:59:51 +08:00 committed by GitHub
parent 184870e2e2
commit 52af9ad188
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Add error message if `Astro.glob` is called outside of an Astro file

View file

@ -4,6 +4,11 @@ import { ASTRO_VERSION } from '../../core/constants.js';
/** Create the Astro.glob() runtime function. */
function createAstroGlobFn() {
const globHandler = (importMetaGlobResult: Record<string, any>, globValue: () => any) => {
if (typeof importMetaGlobResult === 'string') {
throw new Error(
'Astro.glob() does not work outside of an Astro file. Use `import.meta.glob()` instead.'
);
}
let allEntries = [...Object.values(importMetaGlobResult)];
if (allEntries.length === 0) {
throw new Error(`Astro.glob(${JSON.stringify(globValue())}) - no matches found.`);

View file

@ -0,0 +1,13 @@
import { expect } from 'chai';
import { createAstro } from '../../../dist/runtime/server/index.js';
describe('astro global', () => {
it('Glob should error if passed incorrect value', async () => {
const Astro = createAstro(undefined);
expect(() => {
Astro.glob('./**/*.md');
}).to.throw(
'Astro.glob() does not work outside of an Astro file. Use `import.meta.glob()` instead.'
);
});
});