diff options
author | XhmikosR <xhmikosr@gmail.com> | 2020-12-29 23:03:08 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-12-29 23:03:08 +0300 |
commit | 62dfda734c37b8027cb948a2011399fe1a11b723 (patch) | |
tree | 2cd0723c9dde3c42a437b375c230ddea14e87f53 /build | |
parent | ef193608d9bafcf286fec167aba484e75484f135 (diff) |
build-svgs.js: minor tweaks (#602)
* reindent `processFile()`
* rename variables
* cache variable
* add a few comments
* conditionally add the `class`
Diffstat (limited to 'build')
-rw-r--r-- | build/build-svgs.js | 73 |
1 files changed, 39 insertions, 34 deletions
diff --git a/build/build-svgs.js b/build/build-svgs.js index b63911f61..545e97a91 100644 --- a/build/build-svgs.js +++ b/build/build-svgs.js @@ -36,40 +36,45 @@ const getSvgoConfig = async () => { } } -const processFile = (file, config) => new Promise((resolve, reject) => { - file = path.join(iconsDir, file) - - fs.readFile(file, 'utf8') - .then(data => { - const svgo = new SVGO(config) - - svgo.optimize(data) - .then(result => { - const $ = cheerio.load(result.data) - const $svg = $('svg') - - $svg.replaceWith($('<svg>').append($(this).html())) - - for (const [attribute, value] of Object.entries(svgAttributes)) { - $svg.removeAttr(attribute) - $svg.attr(attribute, value) - } - - $svg.attr('class', `bi bi-${path.basename(file, '.svg')}`) - - fs.writeFile(file, $svg.toString(), 'utf8') - .then(() => { - if (VERBOSE) { - console.log(`- ${path.basename(file, '.svg')}`) - } - resolve() - }) - .catch(error => reject(error)) - }) - .catch(error => reject(error)) - }) - .catch(error => reject(error)) -}) +const processFile = (file, config) => { + return new Promise((resolve, reject) => { + const filepath = path.join(iconsDir, file) + const basename = path.basename(file, '.svg') + + fs.readFile(filepath, 'utf8') + .then(data => { + const svgo = new SVGO(config) + + svgo.optimize(data) + .then(result => { + const $ = cheerio.load(result.data) + const $svgElement = $('svg') + + // We keep all SVG contents apart from the `<svg>` element. + // `$(this)` refers to the original object not the replaced one! + $svgElement.replaceWith($('<svg>').append($(this).html())) + + // Then we set the `svgAttributes` in the order we want to, + // hence why we remove the attributes and add them back + for (const [attribute, value] of Object.entries(svgAttributes)) { + $svgElement.removeAttr(attribute) + $svgElement.attr(attribute, attribute === 'class' ? `bi bi-${basename}` : value) + } + + fs.writeFile(filepath, $svgElement.toString(), 'utf8') + .then(() => { + if (VERBOSE) { + console.log(`- ${basename}`) + } + resolve() + }) + .catch(error => reject(error)) + }) + .catch(error => reject(error)) + }) + .catch(error => reject(error)) + }) +} const main = async () => { const basename = path.basename(__filename) |