import SVGO from 'svgo' ; import { Icon } from './types' ; import utils from './utils' ; import defaultSVGConfig from './svgoConfig' ; import path from 'path' ; import fs from 'fs' ; const svgoCache = { } ; export param { string } source param { string } filename param { ( string | string [ ] ) } svgRootPath param { SVGO . Options } svgoConfig returns { Promise < Icon > } export default async function gen ( source , filename , svgRootPath ? , svgoConfig ? ) { if ( ! source ) { source = fs . readFileSync ( filename , { encoding : 'utf8' , } ) ; } svgRootPath = svgRootPath || process . cwd ( ) ; let svgRootPaths = Array . isArray ( svgRootPath ) ? svgRootPath : [ svgRootPath ] ; svgRootPaths = svgRootPaths . map ( ( rp ) => { if ( ! path . isAbsolute ( rp ) ) { return path . join ( process . cwd ( ) , rp ) ; } return rp ; } ) ; const name = path . basename ( filename ) . split ( '.' ) [ 0 ] ; const filePath = utils . getFilePath ( svgRootPaths , filename ) ; const config = defaultSVGConfig ; let key = '' ; if ( svgoConfig && svgoConfig . plugins ) { config . plugins = svgoConfig . plugins ; } if ( config . plugins ) { config . plugins . push ( { cleanupIDs : { remove : true , prefix : 'svgiconid' , } , } ) ; } key = JSON . stringify ( config ) ; let svgo ! ; if ( svgoCache [ key ] ) { svgo = svgoCache [ key ] ; } else { svgo = new SVGO ( config ) ; svgoCache [ key ] = svgo ; } const result = await svgo . optimize ( source ) ; let data = result . data . replace ( /<svg[^>]+>/gi , '' ) . replace ( /<\/svg>/gi , '' ) ; const viewBox = utils . getViewBox ( result ) ; data = utils . addPid ( data ) ; data = utils . renameStyle ( data ) ; data = utils . changeId ( data , filePath , name ) ; data = data . replace ( /'/g , "\\'" ) ; const originalColors = utils . getOriginalColors ( data ) ; const stopColors = utils . getStopColors ( data ) ; const icon = { name : `${ filePath }${ name }` , data : { width : result . info . width , height : result . info . height , viewBox , data , originalColors , stopColors , } , } ; return icon ; }