/
create-symbols.js
executable file
·55 lines (48 loc) · 1.8 KB
/
create-symbols.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
#!/usr/bin/env node
const path = require('path');
const fs = require('fs-extra');
const minimist = require('minimist');
const { createSymbols } = require('../dist/savager.umd.js');
const args = minimist(process.argv.slice(2), {
string: ['input', 'output', 'type'],
alias: { i: 'input', o: 'output', t: 'type' },
default: { t: 'json' },
});
createSymbols(args.input).then(async (symbols) => {
console.info(`processing: ${args.input}`);
if (!symbols || !Object.keys(symbols).length) {
throw new Error(`No svg files found in input directory "${args.input}"`);
}
if (args.input === args.output) {
throw new Error('Cannot overwrite input directory, please provide another directory for output.');
}
await fs.ensureDir(args.output);
await writeSymbolSvgFiles(symbols, { outputDir: args.output });
await writeSymbolReferenceFile(symbols, { outputDir: args.output, type: args.type });
console.info(`Files written to ${args.output}`);
}).catch((err) => { throw new Error(err) });
async function writeSymbolReferenceFile(symbols, { outputDir, type }) {
const json = JSON.stringify(symbols);
const ext = type === 'json' ? 'json' : 'js';
let refString;
switch(type) {
case 'esm':
refString = `export default ${json}`;
break;
case 'cjs':
refString = `module.exports = ${json}`;
break;
default:
refString = json;
}
const filename = path.join(outputDir, `manifest.${ext}`);
await fs.ensureFile(filename);
return fs.writeFile(filename, refString, 'utf-8');
}
async function writeSymbolSvgFiles(symbols, { outputDir }) {
return Promise.all(Object.entries(symbols).map(async ([ name, svgString ]) => {
const filename = path.join(outputDir, `${name}.svg`);
await fs.ensureFile(filename);
return fs.writeFile(filename, svgString, 'utf-8');
}));
}