renderIconsObject.mjs39 lines · main
| 1 | import { basename } from 'path' |
| 2 | import { parseSync } from 'svgson' |
| 3 | import { generateHashedKey, hasDuplicatedChildren, readSvg } from '../utils/helpers.mjs' |
| 4 | |
| 5 | /** |
| 6 | * Build an object in the format: `{ <name>: <contents> }`. |
| 7 | * @param {string[]} svgFiles - A list of filenames. |
| 8 | * @param {Function} getSvg - A function that returns the contents of an SVG file given a filename. |
| 9 | * @returns {Object} |
| 10 | */ |
| 11 | export default (svgFiles, iconsDirectory, renderUniqueKey = false) => |
| 12 | svgFiles |
| 13 | .map((svgFile) => { |
| 14 | const name = basename(svgFile, '.svg') |
| 15 | const svg = readSvg(svgFile, iconsDirectory) |
| 16 | const contents = parseSync(svg) |
| 17 | |
| 18 | if (!(contents.children && contents.children.length)) { |
| 19 | throw new Error(`${name}.svg has no children!`) |
| 20 | } |
| 21 | |
| 22 | if (hasDuplicatedChildren(contents.children)) { |
| 23 | throw new Error(`Duplicated children in ${name}.svg`) |
| 24 | } |
| 25 | |
| 26 | if (renderUniqueKey) { |
| 27 | contents.children = contents.children.map((child) => { |
| 28 | child.attributes.key = generateHashedKey(child) |
| 29 | |
| 30 | return child |
| 31 | }) |
| 32 | } |
| 33 | |
| 34 | return { name, contents } |
| 35 | }) |
| 36 | .reduce((icons, icon) => { |
| 37 | icons[icon.name] = icon.contents |
| 38 | return icons |
| 39 | }, {}) |