Files
svg-iconset/src/app.ts
Konstantin Vulsonov ff1ce12bb7 done first version
2018-09-20 00:58:06 +03:00

58 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createWriteStream, WriteStream } from 'fs';
import { join } from 'path';
import { MainConfig, SVGOConfig, OptimizedResponse } from './config';
import { svgClean } from './modules/svgo.clean';
import { makeConfig, defaultConfig } from './modules/svgo.config';
const SVGO = require('svgo');
export class SvgIconset {
private optimizeConfig: { [prop: string]: boolean }[];
private isValid: boolean = true;
private svgoPlugin: typeof SVGO;
constructor(private config: MainConfig) {
if (config.result === undefined || config.source === undefined) {
this.isValid = false;
}
this.optimizeConfig = config.optimize !== undefined ? makeConfig(config.optimize) : makeConfig();
this.svgoPlugin = new SVGO({
plugins: this.optimizeConfig
});
}
public createSet() {
if (!this.isValid) {
return console.error('Configuration is not valid, check source or result are available');
}
svgClean(this.config.source, this.svgoPlugin)
.then(optimizedResponse => {
let idx = 0;
const ids = optimizedResponse.map(el => el.id);
Promise.all(optimizedResponse.map(el => el.optimized))
.then(resFiles => {
const resultFile = join(process.cwd(), this.config.source, `${this.config.result}-iconset.svg`);
createWriteStream(resultFile)
.once('open', function (this: WriteStream) {
try {
const data = resFiles.map(res => res.data.replace(/<svg /, `<svg id="${ids[idx]}" `));
this.write(`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">${data.join('')}</svg>`);
idx++;
this.end();
} catch (err) {
console.log('ERROR', err);
}
})
.on('close', () => console.log(`Succesfully written file ${resultFile}`))
.on('error', () => console.error('Somethings wrong try again'));
})
.catch(console.error);
})
.catch(err => console.error(err));
}
}