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

eleventy-plugin-og-image

v4.0.1

Published

A plugin to create Open Graph Images from JSX for Eleventy.

Downloads

1,027

Readme

Eleventy Plugin OG Image npm

This plugin helps to create Open Graph images in Eleventy using HTML[^1] within any supported template language and CSS[^2] via satori. No headless browser will be harmed 😉.

Usage

Install the package:

npm install eleventy-plugin-og-image --save-dev

ESM

It's preferred to use this plugin within ESM Eleventy projects. Read more about ESM vs CommonJS on the Eleventy documentation.

import EleventyPluginOgImage from 'eleventy-plugin-og-image';

export default async function (eleventyConfig) {
  eleventyConfig.addPlugin(EleventyPluginOgImage, {
    satoriOptions: {
      fonts: [
        {
          name: 'Inter',
          data: fs.readFileSync('../path/to/font-file/inter.woff'),
          weight: 700,
          style: 'normal',
        },
      ],
    },
  });
}

CommonJS

[!NOTE] This plugin is written in ESM, therefore require is not possible. If the .eleventy.js config uses CommonJS, switch to async and create a dynamic import as shown below.

module.exports = async function (eleventyConfig) {
  const EleventyPluginOgImage = (await import('eleventy-plugin-og-image')).default;

  eleventyConfig.addPlugin(EleventyPluginOgImage, {
    // See above for example config
  });
};

Add a Template

Create an OG-image-template anywhere in the input directory. Use only the supported HTML elements[^1] and CSS properties[^2]. CSS in <style> tags will be inlined, remote images fetched. Shortcode scoped data from the parent template is available. Additionally, some options will be available in the eleventyPluginOgImage key. This is an example og-image.og.njk:

<style>
  .root {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: linear-gradient(135deg, #ef629f, #eecda3);
  }

  .title {
    color: white;
    font-size: 80px;
    margin: auto 0;
  }
</style>

<div class="root">
  <h1 class="title">{{ title }}</h1>
</div>

Call the ogImage shortcode inside the <head> in a template or layout. The first argument is the filePath of the OG-image-template (required, relative to the Eleventy input directory). The second argument is for data (optional). Usage example in Nunjucks, e.g. example-page.njk:

{% ogImage "./og-image.og.njk", { title: "Hello World!" } %}

Result

Generated OG image _site/og-images/s0m3h4sh.png:

Generated OG image

HTML output generated by the shortcode into _site/example-page/index.html (can be modified via the shortcodeOutput option):

<meta property="og:image" content="/og-images/s0m3h4sh.png" />

For applied usage see the example.

[!TIP] The template language of the page and OG-image-template can be mixed or matched.

Configuration

The following options can be passed when adding the plugin:

| Property | Type | Default | | | --------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------ | | inputFileGlob | glob | **/*.og.* | This must match the OG-image-templates to prevent HTML compilation. | | hashLength | number | 8 | | | outputFileExtension | sharp output file formats | png | | | outputDir | string | og-images | Directory into which OG images will be emitted. Relative to eleventy output. | | previewDir | string | ${outputDir}/preview | Directory used for preview during watch or serve. Relative to eleventy output. | | urlPath | string | ${outputDir} | URL-prefix which will be used in returned meta-tags. | | outputFileSlug | function | See source | Generation of the output file slug, must be url safe and exclude the file extension. | | shortcodeOutput | function | See source | Change the HTML returned by the shortcode in pages. | | satoriOptions | satori options | { width: 1200, height: 630, fonts: [] } | If an OG-image-template contains text, it's required to load a font (example). | | sharpOptions | sharp output options | undefined | Options must be corresponding to chosen outputFileExtension. | | OgImage | class CustomOgImage extends OgImage | OgImage | Extend the OgImage class for maximum customization. |

Preview Mode

During development with watch or serve the OG image files are also copied into the previewDir, named by the url slug of the pages they are generated from. Next to it there is a HTML placed which shows the generated HTML, SVG and output image. The previewDir will be deleted during a production build.

Caching

For better performance OG images are cached based on a hash from generated HTML and output options. If the file already exists, further transformations are skipped.

Advanced Usage

Extending OgImage Class

It's possible to extend and overwrite any of the functions from the OgImage class. The custom class is passed as the OgImage parameter to the plugin.

import EleventyPluginOgImage from 'eleventy-plugin-og-image';
import { OgImage } from 'eleventy-plugin-og-image/og-image';

export class CustomOgImage extends BaseOgImage {
  async shortcodeOutput() {
    return this.outputUrl();
  }
}

/** @param {import('@11ty/eleventy/src/UserConfig').default} eleventyConfig */
export default async function (eleventyConfig) {
  eleventyConfig.addPlugin(EleventyPluginOgImage, {
    OgImage: CustomOgImage,
  });
}

Custom Shortcode

A custom shortcode can be created by using the OgImage class.

import { OgImage } from 'eleventy-plugin-og-image/og-image';

const image = await new OgImage({ inputPath, data, options, templateConfig }).render();

Capture Output URL

The plugins shortcode create a meta tag per default, modify the shortcodeOutput option or class function to directly return the outputUrl:

eleventyConfig.addPlugin(EleventyPluginOgImage, {
  async shortcodeOutput(ogImage) {
    return ogImage.outputUrl();
  },
});

Furthermore, it's possible to capture the outputUrl to a variable, e.g. in Nunjucks:

{% setAsync "ogOutputUrl" -%}
    {% ogImage "./og-image.og.njk", { title: "Hello World!" } %}
{%- endsetAsync %}

And use it anywhere afterward with {{ ogOutputUrl }}.

Acknowledgements & Attributions

This plugin is deeply inspired by @vercel/og.

Furthermore, it would not be possible without:

[^1]: Only a subset of HTML elements is supported by satori.

[^2]: Only a subset of CSS properties are supported by yoga-layout, which is used by satori.