You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Create a JS script in folder tools/
I named it update-lqip.js:
constfs=require("fs");constpath=require("path");constyaml=require("js-yaml");// Function to process front matter YAML and update LQIPasyncfunctionprocessFrontMatter(content,lqipMap){constfrontMatterRegex=/^---\n([\s\S]*?)\n---/;constmatch=content.match(frontMatterRegex);if(match){try{constfrontMatter=yaml.load(match[1]);if(frontMatter.image&&frontMatter.image.path){constimagePath=frontMatter.image.path;constlqipData=lqipMap[imagePath];if(lqipData){frontMatter.image.lqip=lqipData;constnewFrontMatter=yaml.dump(frontMatter,{lineWidth: -1,quotingType: '"',forceQuotes: false,noRefs: true,skipInvalid: true,styles: {"!!str": "LITERAL"}});returncontent.replace(frontMatterRegex,`---\n${newFrontMatter}---`);}}}catch(err){console.error("Error processing front matter:",err);}}returncontent;}// Function to process Markdown content and update image LQIPasyncfunctionprocessMarkdown(mdPath,lqipMap){letcontent=awaitfs.promises.readFile(mdPath,"utf8");// Process front matter firstcontent=awaitprocessFrontMatter(content,lqipMap);// Updated regex to handle image with titleconstimageRegex=/!\[.*?\]\((\/assets\/img\/.*?\.webp)(?:\s+"[^"]*")?\)({:[^}]*})?/g;content=content.replace(imageRegex,(match,imagePath,existingAttrs)=>{constlqipData=lqipMap[imagePath];if(lqipData){// Preserve title if it existsconsttitleMatch=match.match(/\(([^)]+)\s+"([^"]+)"\)/);consttitle=titleMatch ? ` "${titleMatch[2]}"` : "";if(existingAttrs){// Extract existing attributes, removing any duplicate lqipconstattrs=existingAttrs.slice(2,-1).replace(/\s*lqip="[^"]*"\s*/g," ").trim();return`![${match.split("![")[1].split("]")[0]}](${imagePath}${title}){: lqip="${lqipData}" ${attrs}}`;}else{return`![${match.split("![")[1].split("]")[0]}](${imagePath}${title}){: lqip="${lqipData}" }`;}}returnmatch;});awaitfs.promises.writeFile(mdPath,content,"utf8");}// Function to scan images and generate LQIP dataasyncfunctiongenerateLQIP(baseDir){console.log("Starting LQIP generation...");constlqip=(awaitimport("lqip-modern")).default;constlqipMap={};asyncfunctionscanDir(dirPath){constdir=awaitfs.promises.opendir(dirPath);forawait(constfileofdir){constfullPath=path.join(dirPath,file.name);if(file.isDirectory()){awaitscanDir(fullPath);}elseif(file.name.endsWith(".webp")){try{constresult=awaitlqip(fullPath);// Create Jekyll-style path (/assets/img/...)constjekyllPath="/"+path.relative(baseDir,fullPath).split(path.sep).join("/");lqipMap[jekyllPath]=result.metadata.dataURIBase64;console.log(`Generated LQIP for: ${jekyllPath}`);}catch(err){console.error(`Error processing file ${fullPath}:`,err);}}}}awaitscanDir(path.join(baseDir,"assets","img"));returnlqipMap;}// Function to scan markdown directories and update LQIPasyncfunctionupdateMarkdownLQIP(markdownDir,lqipMap){constdir=awaitfs.promises.opendir(markdownDir);forawait(constfileofdir){if(file.name.endsWith(".md")){constmdPath=path.join(markdownDir,file.name);try{awaitprocessMarkdown(mdPath,lqipMap);console.log(`Updated LQIP in: ${file.name}`);}catch(err){console.error(`Error processing markdown ${mdPath}:`,err);}}}}// Main executionasyncfunctionmain(){try{// Get the project root directoryconstprojectRoot=process.cwd();// Generate LQIP data for all imagesconstlqipMap=awaitgenerateLQIP(projectRoot);// Update markdown files in both _posts and _tabs directoriesawaitupdateMarkdownLQIP(path.join(projectRoot,"_posts"),lqipMap);awaitupdateMarkdownLQIP(path.join(projectRoot,"_tabs"),lqipMap);console.log("LQIP processing completed successfully!");}catch(err){console.error("Error:",err);}}main();
Checklist
Is your feature request related to a problem? Please describe
LQIP
Describe the solution you'd like
I made a script to generate lqip from images and auto-insert lqip data in blog posts/tabs pages. That handles both frontmatter and content. Like this:
For yaml example, it will process:
And update it to:
For the content, handle cases like:
And convert to:
Or if there are existing attributes:
Will become:
How:
Install 2 dependencies:
"lqip-modern": "^2.2.1",
"js-yaml": "^4.1.0"
Create a JS script in folder tools/
I named it update-lqip.js:
My repo: https://github.com/lotusk08/lotusk08.github.io
My site: https://stevehoang.com
Describe alternatives you've considered
No response
Additional context
The text was updated successfully, but these errors were encountered: