#programmatically reading font data during build

1 messages ยท Page 1 of 1 (latest)

deep citrus
#

Hey ๐Ÿ™‚
I'm struggleing with the new Fonts feature. I'm trying to generate an image during build time (using takumi).
fontData points to dist/_astro/fonts and the font files there are correct and valid.
But reading the font file as described here using await fetch(new URL(font.src[0]!.url, context.url.origin)).then(async (res) => res.arrayBuffer()) returns broken font data.
Any idea how to fix this?

Docs

Looking to add some custom typefaces to an Astro website? Use Google Fonts with Fontsource or add a font of your choice.

queen idol
#

CC @swift sable

swift sable
#

Yes it currently doesn't work at build time unfortunately, I will introduce a new api in the coming weeks for it

#

There was another thread about this with a workaround iirc

deep citrus
#

Oh my bad, sorry ๐Ÿ™ˆ #1484300516065542286 message

deep citrus
#

just for future reference, this is my current workaround:

import { readFile } from 'node:fs/promises'
import { fontData } from 'astro:assets'
import { outDir } from 'astro:config/server'
import type { APIRoute } from 'astro'
import { ImageResponse } from '@takumi-rs/image-response'
import type { FontDetails } from '@takumi-rs/core'

import ogImage from '../og-image'

export const GET: APIRoute = async (context) => {
  const fonts: FontDetails[] = await Promise.all(
    fontData['--font-montserrat'].map(async (font) => ({
      name: 'Montserrat',
      weight: Number(font.weight),
      style: font.style as any,
      data: import.meta.env.DEV
        ? await fetch(new URL(font.src[0]!.url, context.url.origin)).then(
            (res) => res.arrayBuffer(),
          )
        : await readFile(new URL(`.${font.src[0]!.url}`, outDir)),
    })),
  )

  return new ImageResponse(ogImage(), {
    width: 1200,
    height: 630,
    format: 'png',
    fonts,
  })
}

It seems like takumi does not pick up the font specified in tailwind with

@theme inline {  --font-sans: var(--font-montserrat); }

therefore I needed to specify the font-family directly using style={{ fontFamily: 'Montserrat' }} inside my jsx template