Skip to content

Instantly share code, notes, and snippets.

@lusiakpurnama
Last active August 24, 2021 13:37
Show Gist options
  • Save lusiakpurnama/46d27c069928aea434fc46fa82a68bce to your computer and use it in GitHub Desktop.
Save lusiakpurnama/46d27c069928aea434fc46fa82a68bce to your computer and use it in GitHub Desktop.
Replace svg using gulp-replace and cheerio
const {
src, dest, task, lastRun,
} = require('gulp');
const replace = require('gulp-replace');
const fs = require('fs');
const cheerio = require('cheerio');
const srcDir = 'src';
const buildDir = 'build';
// Template files here
const files = [
`${srcDir}/*.liquid`,
]
const templateFiles = function () {
return src(files.theme, { since: lastRun(templateFiles) })
/*
Use this regex if not using different folders to keep the svg
/<img[^>]*?replace-to-svg=""[^>]*?>/
or
/<img[^>]*?replace-to-svg[^>]*?>/
*/
.pipe(replace(/<img[^>]*?replace-to-svg="(folder1|folder2)"[^>]*?>/, (match, p1) => {
let result = match;
// can directly use const if not using different folders
let folder = '';
if (p1 === 'folder1') {
folder = 'src/folder1';
} else if (p1 === 'folder2') {
folder = 'node_modules/folder2';
}
const img = cheerio.load(match);
const attrs = img('img').attr();
if (attrs.src && attrs.src !== '') {
let svg;
try {
svg = fs.readFileSync(`${folder}/${attrs.src}`, { encoding: 'utf8' });
} catch (error) {
console.log('Inject SVG error:', `${folder}/${attrs.src}`);
return result;
}
svg = cheerio.load(svg);
Object.keys(attrs).forEach((attr) => {
if (!['src', 'replace-to-svg'].includes(attr)) {
svg('svg').attr(attr, attrs[attr]);
}
});
result = svg('svg').prop('outerHTML');
}
return result;
}))
.pipe(dest(buildDir));
};
task(templateFiles);
@lusiakpurnama
Copy link
Author

@benwakeford This is the gulp task I created as a workaround for the svg embed plugin.

@benwakeford
Copy link

@lusiakpurnama Very slick! That's a great solution to the non-html template problem in gulp-embed-svg. With a bit of tweaking, that could be worked up to be nice alternative plugin. In the meantime, it's a great workaround 🙂

Thanks for bringing it to my attention. I'll cross-post it to the issue I started for others to see.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment