npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

svelte-component-to-image

v1.0.16

Published

A package for easily rendering .png images from svelte components in SvelteKit. Inspired by Vercel's [`OG Image Generation`](https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation) tool.

Downloads

1,232

Readme

svelte-component-to-image

A package for easily rendering .png images from svelte components in SvelteKit. Inspired by Vercel's OG Image Generation tool.

Good for rendering dynamic Open Graph images quickly and effeciently without having to use canvas.

Demo

Features

  • Renders a normal svelte component as a png
  • Component props are supported for dynamic image generation
  • Use basic CSS like flexbox and absolute positioning (See valid CSS)
  • Lightweight and fast (doesn't use canvas or puppeteer)
  • Load custom fonts: tff, otf, woff accepted (woff2 not accepted currently)

Svelte 5 Usage

The svelte 5 version will be available as the 1.0.0+ release.

You will need to add <svelte:options css="injected" /> to every component you want to render as an image. You will see an error if you don't and the component will not render.

Warning

There is currently a bug with the Svelte 5 version deep in a dependency that will render radial gradients fine in dev but will crash production. I am working on a fix.

Svelte 4 Usage

The Svelte 4 version is available as the 0.1.0 release.

Installation

npm install svelte-component-to-image

Tested On

  • Vercel (working)
  • Netlify (working)
  • Cloudflare Pages (not working)

Usage

This package is NOT for rendering normal svelte components as images, you will need to write your components with image rendering in mind. The guidelines are set by (Satori's CSS Guidelines) - you will need to write your markup and css with these factors in mind.

Create A Component

Create a .svelte component with JS/HTML/CSS. You can pass props or use additional technologies that require preproccesors like TypeScript or SASS.

HelloWorld.svelte

<script lang="ts">
	export let text: string = 'hello';
</script>

<div id="container">
	<h1>
		{text} world!
	</h1>
</div>

<style>
	* {
		display: flex; /* if you're having problems with satori errors, this line can really help */
	}
	#container {
		width: 1200px;
		height: 600px;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		background: rgb(63, 94, 251);
		background: radial-gradient(circle, rgba(63, 94, 251, 1) 0%, rgba(252, 70, 107, 1) 100%);
	}
	h1 {
		color: red;
		font-size: 75px;
	}
</style>

+server.ts Endpoint

Create a +server.ts endpoint to render and serve the image. Import the package and options type.

More on how the font importing works below.

image/+server.ts

import { error } from '@sveltejs/kit'
import type { RequestHandler } from './$types'

// Svelte Component To Image
import { image_from_component, type RenderOptions } from 'svelte-component-to-image'

// Normal .svelte component
import HelloWorld from './HelloWorld.svelte'

export const GET: RequestHandler = (async ({url}) => {
    try {
        const options: RenderOptions = {
            width: 1200,
            height: 600,
            props: {
                text: url.searchParams.get('text') ?? 'text not found'
            },
            fonts: [
                {
                    name: 'Typewriter',
                    url: `${url.origin}/TYPEWR__.TTF`,
                    weight: 400,
                    style: 'normal'
                }
            ],
            debug: false // you can omit this or set it to true to see logs of data, it can help for debug edge cases
        }

        // pass the component and options to the package
        const image    = await image_from_component(HelloWorld, options)
        const response = new Response(image)
        if(!dev){
            // caching on dev will make it hard to see iterations
            response.headers.append('Content-Type', 'image/png')
            response.headers.append('Cache-Control', 's-maxage=604800, stale-while-revalidate=604800')
        }
        return response
    } catch (e) {
        console.error(e)
        throw error(500, 'Error trying to generate image from component.')
    }
}) satisfies RequestHandler

Font Importing

You can import as many ttf, otf, and woff fonts as you want to use inside of your component. Although, importing 100 fonts is going to affect server load and speed.

woff2 files are not currently supported.

Fonts files can be local or remote. They need a full URL to be properly loaded. Local fonts stored in /static can be loaded using ${url.origin}/ as long as {url} is made available in the endpoint.

Once the font is loaded, you can reference them in the CSS using font-family. If only one font is loaded, it will be the default.

Not All Fonts Work!

Not all fonts work! If a font fails to load it will break the image rendering. I am not sure what causes this or which fonts are "approved" - but I have had luck using Font Squirrel's Webfont Generator to convert fonts to web-safe formats and using those.

Images

Images can be used and rendered like normal. You will want to set the height and width.

<img src="https://picsum.photos/200/300" width="200" height="300" />

More info

This uses Vercel's Satori. You can find out more about what is and isn't supported by reading it's docs: Vercel's Satori

License

MIT