-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-svg-sprite.js
72 lines (59 loc) · 1.77 KB
/
generate-svg-sprite.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
64
65
66
67
68
69
70
71
72
const fs = require('fs');
const path = require('path');
const SvgSpriter = require('svg-sprite');
const ICONS_PATH = 'src/assets/icons';
const SVG_SPRITE_PATH = 'src/assets/sprite';
const SVG_SPRITE_FILENAME = 'svg-sprite.svg';
const spriter = new SvgSpriter({
/* Main output directory */
dest: SVG_SPRITE_PATH,
mode: {
css: {
render: {
css: false,
},
},
},
svg: {
/* Add namespace token to all CSS class names in SVG shapes */
namespaceClassnames: false,
},
});
/* Get list of SVG files in directory */
function getSvgFiles(dirPath, arrayOfFiles) {
const files = fs.readdirSync(dirPath)
arrayOfFiles = arrayOfFiles || []
files.forEach((file) => {
const isDirectory = fs.statSync(`${ dirPath }/${ file }`).isDirectory();
if (isDirectory) {
arrayOfFiles = getSvgFiles(`${ dirPath }/${ file }`, arrayOfFiles);
} else if (path.extname(file) === '.svg') {
arrayOfFiles.push(path.join(dirPath, '/', file));
}
})
return arrayOfFiles;
}
const svgFiles = getSvgFiles(ICONS_PATH);
/* Add SVG files to sprite */
svgFiles.forEach((svgFile) => {
const svgPath = path.relative(ICONS_PATH, svgFile);
spriter.add(
svgPath,
path.basename(svgFile),
fs.readFileSync(svgFile, { encoding: 'utf-8' }),
);
});
/* Compile the sprite */
spriter.compile((error, result) => {
const destFolder = path.dirname(path.join(spriter.config.dest, SVG_SPRITE_FILENAME));
/* Create the destination folder if it doesn't exist */
fs.mkdir(destFolder, { recursive: true }, (error) => {
if (error) { throw error; }
/* Write the generated sprite to folder */
fs.writeFile(
path.join(spriter.config.dest, SVG_SPRITE_FILENAME),
result.css.sprite.contents,
(err) => { if (err) throw err; },
);
});
});