-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildSVG.js
63 lines (53 loc) · 1.77 KB
/
buildSVG.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Creates SVG sprites from the SVG files in the /img folder
*/
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
import recurse from 'recursive-readdir';
import spriter from 'svg2sprite';
const { readFile } = fs.promises;
const currentDir = path.dirname(fileURLToPath(import.meta.url));
const spriteOptions = {
iconPrefix: `svg-`,
inline: true,
};
/**
* Creates a sprite from an SVG string
* @param {Object} info
* @param {String} info.name The name of the SVG
* @param {String} info.svg The SVG, as a string
* @return {Object} Returns an object with "name" and "sprite" properties
*/
function createSprite({ name, svg }) {
const collection = spriter.collection(spriteOptions);
collection.add(name, svg);
const sprite = collection.compile();
return { name, sprite };
}
/**
* Reads a single SVG file
* @param {String} filePath Path to the SVG file
* @return {Object} Returns a hash with "name" and "svg" properties
*/
async function readSVG(filePath) {
const svg = await readFile(filePath, `utf8`);
const name = path.basename(filePath, `.svg`).replace(`.`, `-`);
return { name, svg };
}
/**
* A singleton that returns a hash of sprites
* @return {Object} Returns the hash of sprites
*/
export default async function createSprites() {
// add local SVG files
const imageFiles = await recurse(path.join(currentDir, `../src/img`));
const svgFiles = imageFiles.filter(filePath => path.extname(filePath) === `.svg`);
const svgs = await Promise.all(svgFiles.map(readSVG));
return svgs
.map(createSprite)
.reduce((hash, { name, sprite }) => {
hash[name] = sprite; // eslint-disable-line no-param-reassign
return hash;
}, {});
}