From 87ab9c43a74146fb8fc604c49a34a7d465cfb4d4 Mon Sep 17 00:00:00 2001 From: Eric Cornelissen Date: Thu, 15 Aug 2019 13:23:35 +0200 Subject: [PATCH] Refactor prepublish script to use template file for icon objects (#1547) * Refactor prepublish script to use template file for icon objects ... to hopefully increase readability * Fix build and test issues * Add missing semi-colon * Explicitly check for errors when writing individual static .js files --- scripts/build-package.js | 35 ++++++++++++++++++++++++-------- scripts/templates/icon-object.js | 10 +++++++++ 2 files changed, 36 insertions(+), 9 deletions(-) create mode 100644 scripts/templates/icon-object.js diff --git a/scripts/build-package.js b/scripts/build-package.js index 287b2f2e..74b5d78d 100644 --- a/scripts/build-package.js +++ b/scripts/build-package.js @@ -11,10 +11,17 @@ const fs = require("fs"); const util = require("util"); const minify = require("uglify-js").minify; +const UTF8 = "utf8"; + const dataFile = "../_data/simple-icons.json"; const indexFile = `${__dirname}/../index.js`; const iconsDir = `${__dirname}/../icons`; + const indexTemplateFile = `${__dirname}/templates/index.js`; +const iconObjectTemplateFile = `${__dirname}/templates/icon-object.js`; + +const indexTemplate = fs.readFileSync(indexTemplateFile, UTF8); +const iconObjectTemplate = fs.readFileSync(iconObjectTemplateFile, UTF8); const data = require(dataFile); const { titleToFilename } = require("./utils"); @@ -27,27 +34,37 @@ function iconToKeyValue(icon) { return `'${icon.title}':${iconToObject(icon)}`; } function iconToObject(icon) { - return `{title:'${escape(icon.title)}',slug:'${escape(icon.slug)}',svg:'${escape(icon.svg)}',get path(){return this.svg.match(/ { const filename = titleToFilename(icon.title); - icon.svg = fs.readFileSync(`${iconsDir}/${filename}.svg`, "utf8"); + icon.svg = fs.readFileSync(`${iconsDir}/${filename}.svg`, UTF8); icon.slug = filename; - icons.push(icon) + icons.push(icon); // write the static .js file for the icon - fs.writeFileSync( - `${iconsDir}/${filename}.js`, - `module.exports=${iconToObject(icon)};` - ); + const { error, code } = minify(`module.exports=${iconToObject(icon)};`); + if (error) { + console.error(error); + process.exit(1); + } else { + fs.writeFileSync(`${iconsDir}/${filename}.js`, code); + } + }); // write our generic index.js -const indexTemplate = fs.readFileSync(indexTemplateFile, "utf8"); -const { error, code } = minify(util.format(indexTemplate, icons.map(iconToKeyValue).join(','))); +const rawIndexJs = util.format(indexTemplate, icons.map(iconToKeyValue).join(',')); +const { error, code } = minify(rawIndexJs); if (error) { console.error(error); process.exit(1); diff --git a/scripts/templates/icon-object.js b/scripts/templates/icon-object.js new file mode 100644 index 00000000..407316ea --- /dev/null +++ b/scripts/templates/icon-object.js @@ -0,0 +1,10 @@ +{ + title: '%s', + slug: '%s', + svg: '%s', + get path() { + return this.svg.match(/