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

Cannot access 'getCollection' before initialization when running build #8972

Closed
1 task
MrAlex94 opened this issue Nov 1, 2023 · 4 comments
Closed
1 task
Labels
needs triage Issue needs to be triaged

Comments

@MrAlex94
Copy link

MrAlex94 commented Nov 1, 2023

Astro Info

Astro                    v3.4.0
Node                     v20.7.0
System                   macOS (arm64)
Package Manager          bun
Output                   static
Adapter                  none
Integrations             starlight-blog
                         @astrojs/starlight
                         @astrojs/svelte
                         @astrojs/tailwind

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

I am generating a open graph image with src/pages/open-graph/[...path].ts:

import { OGImageRoute } from 'astro-og-canvas'
import { getCollection } from 'astro:content'

const allPages = await getCollection('docs')

/** Paths for all of our Markdown content we want to generate OG images for. */
const paths = process.env.SKIP_OG ? [] : allPages

/** An object mapping file paths to file metadata. */
const pages = Object.fromEntries(paths.map(({ id, slug, data }) => [id, { data, slug }]))

export const { getStaticPaths, GET } = OGImageRoute({
	param: 'path',

	pages,

	getImageOptions: async (_, { data, slug }: (typeof pages)[string]) => {
		return {
			title: data.title,
			description: data.description,
			dir: slug,
			logo: {
				path: './src/assets/waterfox-logo.png',
				size: [400]
			},
			border: { color: [5, 51, 97], width: 20, side: 'inline-start' },
			bgGradient: [
				[182, 156, 254],
				[123, 165, 255]
			],
			font: {
				title: {
					size: 80,
					families: ['Montserrat'],
					weight: 'Bold'
				},
				description: {
					size: 40,
					lineHeight: 1.25,
					families: ['Montserrat Thin'],
					weight: 'Light'
				}
			},
			fonts: [
				'https://github.com/JulietaUla/Montserrat/raw/master/fonts/webfonts/Montserrat-Light.woff2',
				'https://github.com/JulietaUla/Montserrat/raw/master/fonts/webfonts/Montserrat-Bold.woff2'
			]
		}
	}
})

When running bun run build, I get the following output:

 generating static routes 
 error   Cannot access 'getCollection' before initialization
  File:
    /Users/akontos/Work/waterfox-rework/node_modules/astro/dist/core/build/generate.js:193:22
  Code:
    192 |   }
    > 193 |   const pageModule = await pageModulePromise();
          |                      ^
      194 |   if (shouldSkipDraft(pageModule, pipeline.getSettings())) {
      195 |     logger.info(null, `${magenta("\u26A0\uFE0F")}  Skipping draft ${pageData.route.component}`);
      196 |     logger.warn(
  Stacktrace:
ReferenceError: Cannot access 'getCollection' before initialization
    at file:///Users/akontos/Work/waterfox-rework/dist/chunks/pages/__2d08d290.mjs:279:18
    at ModuleJob.run (node:internal/modules/esm/module_job:217:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:308:24)
    at async generatePage (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/core/build/generate.js:193:22)
    at async generatePages (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/core/build/generate.js:147:9)
    at async staticBuild (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/core/build/static-build.js:85:7)
    at async AstroBuilder.build (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/core/build/index.js:127:5)
    at async AstroBuilder.run (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/core/build/index.js:158:7)
    at async build (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/core/build/index.js:37:3)
    at async build (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/cli/build/index.js:21:3)
    at async runCommand (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/cli/index.js:116:7)
    at async cli (file:///Users/akontos/Work/waterfox-rework/node_modules/astro/dist/cli/index.js:144:5)

error: script "build" exited with code 1 (SIGHUP)

What's the expected result?

bun run astro dev generates the images correctly. bun run build should also, I am unsure why getCollection would not be available/uninitialized at build time?

Link to Minimal Reproducible Example

https://stackblitz.com/edit/github-2zqutw

Participation

  • I am willing to submit a pull request for this issue.
@github-actions github-actions bot added the needs triage Issue needs to be triaged label Nov 1, 2023
@vasfvitor
Copy link
Contributor

vasfvitor commented Nov 14, 2023

edit: minimal https://stackblitz.com/edit/starlight-getcollection

I'm having the same issue, works on dev but can't build.

Tried to reproduce without Starlight but couldn't. And this work perfectly on official Astro docs, as it is from I copied got inspiration for the implementation.

I went as far as adding editing Starlight source code (instead of override) but no difference, I guess any override will give the same result, I've tried with head and banner:

Steps on a new Starlight Project:

  1. Override onastro.config.mjs
components: {
  Footer: './src/components/overrides/test.astro',
  },
  1. Component: src/components/overrides/test.astro
---
import { sum } from 'src/pages/thisFile';
sum();
---
  1. src/pages/thisFile.ts. Needs to be in /pages because the goals to utilize a [...docs].ts). Either way will fail.
    Note: placing thisFile.ts outside /pages works, but I haven't tried to use it as workaround.
import { getCollection } from 'astro:content';
const pages= await getCollection('docs');
console.log(pages);

export function sum() {
  1 - 1
}
  1. pnpm build
  2. Fail
    image

The very same function works when called from a file outside /pages, instead of an override, I haven't tried calling it from components.

example:
src/pages/test.astro

---
import { sum } from 'src/pages/thisFile';
sum();
---

Hope this helps to triage

@matthewp
Copy link
Contributor

Hello, unfortunately this is a limitation of how Astro components work. The getStaticPaths function is lifted out and does not have access to the scope values. So you must perform all of your logic inside of getStaticPaths. This is explained here: https://docs.astro.build/en/reference/api-reference/#getstaticpaths

@barrenechea
Copy link

I wonder how withastro/docs is doing it, the code seems to have a very similar implementation for OpenGraph, just importing it from ~/content.

When I attempt to do the same on my project, it fails for the same reason as this issue.

@vasfvitor
Copy link
Contributor

vasfvitor commented Nov 30, 2023

for context, this is a PR from Astro Docs migration to Starlight, it's in active development as of now and in the future this hack may not be needed anymore.

00 hack: withastro/docs@030073f thanks Delucis!
This helped to solve the current issue, well, at least solved there and I've test and now it builds yaaay! for reference I'm using a simplified version of the current Astro Docs setup, so ymmv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs triage Issue needs to be triaged
Projects
None yet
Development

No branches or pull requests

4 participants