renderIconsObject.mjs39 lines · main
1import { basename } from 'path'
2import { parseSync } from 'svgson'
3import { 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 */
11export 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 }, {})