|
| 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