From caf8c910d38f4f213a1184c5156c21a3f9239519 Mon Sep 17 00:00:00 2001 From: madrilene Date: Wed, 31 Jan 2024 11:26:13 +0100 Subject: [PATCH] change how og images are handled --- config/events/index.js | 49 +++++++++++++++++++++++------------------- eleventy.config.js | 4 ++-- 2 files changed, 29 insertions(+), 24 deletions(-) diff --git a/config/events/index.js b/config/events/index.js index d089fd0..b6723c9 100644 --- a/config/events/index.js +++ b/config/events/index.js @@ -1,30 +1,35 @@ // https://bnijenhuis.nl/notes/automatically-generate-open-graph-images-in-eleventy/ -// concerts SVG to JPEG for open graph images +// https://github.com/sophiekoonin/localghost/blob/main/src/plugins/og-to-png.js +// converts SVG to JPEG for open graph images +const fsPromises = require('fs/promises'); const fs = require('fs'); +const path = require('path'); const Image = require('@11ty/eleventy-img'); +const ogImagesDir = './src/assets/og-images'; -const svgToJpeg = function () { - const ogImagesDir = 'dist/assets/og-images/'; - fs.readdir(ogImagesDir, (err, files) => { - if (!!files && files.length > 0) { - files.forEach(fileName => { - if (fileName.endsWith('.svg')) { - let imageUrl = ogImagesDir + fileName; - Image(imageUrl, { - formats: ['jpeg'], - outputDir: './' + ogImagesDir, - filenameFormat: function (id, src, width, format, options) { - let outputFileName = fileName.substring(0, fileName.length - 4); - return `${outputFileName}.${format}`; - } - }); - } - }); - } else { - console.log('⚠ No social images found'); - } - }); +const svgToJpeg = async function () { + const socialPreviewImagesDir = 'dist/assets/og-images/'; + const files = await fsPromises.readdir(socialPreviewImagesDir); + if (files.length > 0) { + files.forEach(function (filename) { + const outputFilename = filename.substring(0, filename.length - 4); + if ( + filename.endsWith('.svg') & !fs.existsSync(path.join(ogImagesDir, outputFilename)) + ) { + const imageUrl = socialPreviewImagesDir + filename; + Image(imageUrl, { + formats: ['jpeg'], + outputDir: ogImagesDir, + filenameFormat: function (id, src, width, format, options) { + return `${outputFilename}.${format}`; + } + }); + } + }); + } else { + console.log('⚠ No social images found'); + } }; module.exports = { diff --git a/eleventy.config.js b/eleventy.config.js index 3f29b27..1f971aa 100644 --- a/eleventy.config.js +++ b/eleventy.config.js @@ -114,8 +114,8 @@ module.exports = eleventyConfig => { // --------------------- Passthrough File Copy ----------------------- // same path - ['src/assets/fonts/', 'src/assets/images/template'].forEach(path => - eleventyConfig.addPassthroughCopy(path) + ['src/assets/fonts/', 'src/assets/images/template', 'src/assets/og-images'].forEach( + path => eleventyConfig.addPassthroughCopy(path) ); // to root