refactor: ♻️ provide generalized function for meta image generation
Separate functions would work almost identical, so might as well merge into single function and generalize it
This commit is contained in:
parent
bd4dbdd620
commit
bcd125d951
3 changed files with 40 additions and 21 deletions
|
@ -7,13 +7,11 @@ import markdownIt from 'markdown-it';
|
|||
|
||||
const MARKDOWNIT_OPTIONS = { html: true, linkify: true, typographer: true };
|
||||
const IMAGE_TRANSFORM_OPTS = {
|
||||
// Set global default options
|
||||
formats: ['avif', 'webp', 'auto'],
|
||||
sharpJpegOptions: { mozjpeg: true, optimiseScans: true, quality: 95 },
|
||||
sharpPngOptions: { compressionLevel: 9 },
|
||||
urlPath: '/img/',
|
||||
// Notably `outputDir` is resolved automatically
|
||||
// to the project output directory
|
||||
outputDir: './public/img/',
|
||||
defaultAttributes: {
|
||||
loading: 'lazy',
|
||||
decoding: 'async',
|
||||
|
@ -24,20 +22,34 @@ const IMAGE_TRANSFORM_OPTS = {
|
|||
const BASE = env.ELEVENTY_PRODUCTION ? 'https://ref.sebin-nyshkim.net' : 'http://localhost:8080';
|
||||
|
||||
// source: https://notes.jays.net/blog/11ty/
|
||||
async function getOgImage(src, key) {
|
||||
const stats = await Image(src, {
|
||||
width: [1200],
|
||||
formats: ['webp'],
|
||||
urlPath: '/img/',
|
||||
outputDir: './public/img/',
|
||||
filenameFormat: (hash, src, width, format) => `${hash}-${width}.${format}`
|
||||
});
|
||||
async function getImage(type, src, key) {
|
||||
let widths, formats;
|
||||
|
||||
if (key === 'url') {
|
||||
return BASE + stats.webp[0][key];
|
||||
switch (type) {
|
||||
case 'og':
|
||||
widths = [1200];
|
||||
formats = ['webp'];
|
||||
break;
|
||||
case 'favicon':
|
||||
widths = [200];
|
||||
formats = ['png'];
|
||||
break;
|
||||
}
|
||||
|
||||
return stats.webp[0][key];
|
||||
const opts = {
|
||||
...IMAGE_TRANSFORM_OPTS,
|
||||
widths,
|
||||
formats
|
||||
};
|
||||
|
||||
const stats = await Image(src, opts);
|
||||
const [format] = formats;
|
||||
|
||||
if (key === 'url') {
|
||||
return BASE + stats[format][0][key];
|
||||
}
|
||||
|
||||
return stats[format][0][key];
|
||||
}
|
||||
|
||||
export default async function (eleventyConfig) {
|
||||
|
@ -72,7 +84,7 @@ export default async function (eleventyConfig) {
|
|||
return content;
|
||||
});
|
||||
|
||||
eleventyConfig.addFilter('getOgImage', getOgImage);
|
||||
eleventyConfig.addFilter('getImage', getImage);
|
||||
|
||||
eleventyConfig.addPlugin(eleventyPluginWebc, {
|
||||
components: ['src/components/**/*.webc', 'npm:@11ty/eleventy-img/*.webc'],
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue