11#!/usr/bin/env node
22
3- import { exec } from 'child_process' ;
43import { existsSync , promises as fs } from 'fs' ;
54import { extname , resolve , basename } from 'path' ;
65
76import { load } from 'cheerio' ;
87import { Command } from 'commander' ;
8+ import { optimize , loadConfig } from 'svgo' ;
99
1010const { rm, readdir, readFile, writeFile } = fs ;
1111
1212const cli = new Command ( ) ;
1313
1414const SVG_PROPS = 'xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true"' ;
15- const SVG_STYLE = 'style="width: 0; height: 0; visibility: hidden; position: absolute;"' ;
15+ const SVG_STYLE = 'style="width: 0; height: 0; position: absolute;"' ;
16+ const DEFAULT_CONFIG = './config/svgo.config.js' ;
17+
18+ const CHEERIO_OPTIONS = {
19+ lowerCaseTags : true ,
20+ lowerCaseAttributeNames : true ,
21+ _useHtmlParser2 : true
22+ } ;
1623
1724cli . option ( '-i, --input [input]' , 'Specifies input dir (current dir by default)' , '.' )
1825 . option ( '-o, --output [output]' , 'Specifies output file ("./sprite.svg" by default)' , 'sprite.svg' )
@@ -24,7 +31,7 @@ cli.option('-i, --input [input]', 'Specifies input dir (current dir by default)'
2431const { input : INPUT , output : OUTPUT , viewbox : VIEWBOX , prefix : PREFIX , quiet : QUIET , config : CONFIG } = cli . opts ( ) ;
2532
2633const onEnd = ( ) : void => console . log ( `File ‘${ OUTPUT } ’ successfully generated.` ) ;
27- const getSvg = ( content : string ) => load ( content ) ( 'svg' ) . first ( ) ;
34+ const getSvg = ( content : string ) => load ( content , CHEERIO_OPTIONS ) ( 'svg' ) . first ( ) ;
2835const filterFile = ( file : string ) => extname ( file ) === '.svg' ;
2936const processFiles = ( files : string [ ] ) => Promise . all ( files . filter ( filterFile ) . map ( processFile ) ) ;
3037const removeOutput = async ( ) => ( existsSync ( OUTPUT ) ? await rm ( OUTPUT ) : undefined ) ;
@@ -66,8 +73,18 @@ const onError = (err: Error) => {
6673
6774removeOutput ( )
6875 . then ( readSrcFolder )
69- . then ( ( files : string [ ] ) => {
70- exec ( `svgo-viewbox -i ${ INPUT } -f ${ CONFIG } ` ) ;
76+ . then ( async ( files : string [ ] ) => {
77+ let svgoConfig = await loadConfig ( DEFAULT_CONFIG ) ;
78+
79+ try {
80+ svgoConfig = await loadConfig ( CONFIG ) ;
81+ } catch ( e : any ) {
82+ console . log ( 'SVG Symbol Sprite: SVGO configuration file not found. Using default SVGO configuration.' ) ;
83+ }
84+
85+ for ( const file of files ) {
86+ optimize ( file , svgoConfig ) ;
87+ }
7188
7289 return processFiles ( files ) ;
7390 } )
0 commit comments