Skip to content

Commit ae164db

Browse files
colebemisCole Bemis
authored andcommitted
build: Add script to build dist/icons.json
1 parent c089ee1 commit ae164db

File tree

3 files changed

+84
-0
lines changed

3 files changed

+84
-0
lines changed

.babelrc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"presets": [
3+
"es2015"
4+
]
5+
}

Makefile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
node_modules:
2+
npm install
3+
4+
dist:
5+
mkdir dist
6+
7+
dist/icons.json: node_modules dist icons icons/*.svg
8+
./node_modules/.bin/babel-node bin/build-json.js

bin/build-json.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* @file Builds `icons.json` from `icons` directory.
3+
*/
4+
5+
/* eslint-disable import/no-extraneous-dependencies */
6+
import fs from 'fs';
7+
import path from 'path';
8+
import RSVP from 'rsvp';
9+
import Svgo from 'svgo';
10+
import parse5 from 'parse5';
11+
12+
const svgFiles = fs.readdirSync(path.resolve(__dirname, '../icons'))
13+
.filter(file => path.extname(file) === '.svg');
14+
15+
buildIconsObject(svgFiles)
16+
.then(icons => {
17+
fs.writeFileSync(
18+
path.resolve(__dirname, '../dist/icons.json'),
19+
JSON.stringify(icons),
20+
);
21+
});
22+
23+
/**
24+
* Build an icons object in the format: `{ <icon name>: <svg content> }`.
25+
* @param {string[]} svgFiles - A list of file names.
26+
* @returns {RSVP.Promise<Object>}
27+
*/
28+
function buildIconsObject(svgFiles) {
29+
const icons = {};
30+
31+
svgFiles.forEach(svgFile => {
32+
const svg = fs.readFileSync(path.resolve(__dirname, '../icons', svgFile), 'utf8');
33+
const key = path.basename(svgFile, '.svg');
34+
35+
icons[key] = optimizeSvg(svg)
36+
.then(optimizedSvg => getSvgContent(optimizedSvg));
37+
});
38+
39+
return RSVP.hash(icons);
40+
}
41+
42+
/**
43+
* Optimize SVG with `svgo`.
44+
* @param {string} svg - An SVG string.
45+
* @returns {RSVP.Promise<string>}
46+
*/
47+
function optimizeSvg(svg) {
48+
// configure svgo
49+
const svgo = new Svgo({
50+
plugins: [
51+
{ convertShapeToPath: false },
52+
{ mergePaths: false },
53+
{ removeAttrs: { attrs: '(fill|stroke.*)' } },
54+
],
55+
});
56+
57+
return new RSVP.Promise(resolve => {
58+
svgo.optimize(svg, ({ data }) => resolve(data));
59+
});
60+
}
61+
62+
/**
63+
* Get content between opening and closing `<svg>` tags.
64+
* @param {string} svg - An SVG string.
65+
* @returns {string}
66+
*/
67+
function getSvgContent(svg) {
68+
const fragment = parse5.parseFragment(svg);
69+
const content = parse5.serialize(fragment.childNodes[0]);
70+
return content;
71+
}

0 commit comments

Comments
 (0)