|
| 1 | +import chalk from 'chalk'; |
| 2 | +import * as path from 'path'; |
| 3 | +import { svgo } from '../svgo'; |
| 4 | + |
| 5 | +import { |
| 6 | + generateInterfaceDefinition, |
| 7 | + generateSvgConstant, |
| 8 | + generateTypeDefinition, |
| 9 | + generateTypeName, |
| 10 | + generateVariableName |
| 11 | +} from '../generators/generators'; |
| 12 | +import { getFilePathsFromRegex } from '../regex-helpers'; |
| 13 | +import { extractSvgContent, writeIconsFile } from '../file-helpers'; |
| 14 | +import { ConvertionOptions } from '../../bin/svg-to-ts'; |
| 15 | + |
| 16 | +const typesDelimitor = ' | '; |
| 17 | + |
| 18 | +export const convertToMultipleFiles = async (convertionOptions: ConvertionOptions): Promise<void> => { |
| 19 | + const { typeName, prefix, delimiter, interfaceName, outputDirectory, srcFiles, fileName } = convertionOptions; |
| 20 | + let svgConstants = ''; |
| 21 | + let types = generateTypeDefinition(typeName); |
| 22 | + |
| 23 | + try { |
| 24 | + const filePaths = await getFilePathsFromRegex(srcFiles); |
| 25 | + for (let i = 0; i < filePaths.length; i++) { |
| 26 | + const fileNameWithEnding = path.basename(filePaths[i]); |
| 27 | + const [filenameWithoutEnding, extension] = fileNameWithEnding.split('.'); |
| 28 | + |
| 29 | + if (extension === 'svg') { |
| 30 | + const rawSvg = await extractSvgContent(filePaths[i]); |
| 31 | + const optimizedSvg = await svgo.optimize(rawSvg); |
| 32 | + const variableName = generateVariableName(prefix, filenameWithoutEnding); |
| 33 | + const typeName = generateTypeName(filenameWithoutEnding, delimiter); |
| 34 | + const svgConstant = generateSvgConstant(variableName, interfaceName, typeName, optimizedSvg.data); |
| 35 | + |
| 36 | + await writeIconsFile(outputDirectory, `${prefix}-${filenameWithoutEnding}.icon`, svgConstant); |
| 37 | + |
| 38 | + svgConstants += svgConstant; |
| 39 | + types += i === filePaths.length - 1 ? `'${typeName}';` : `'${typeName}'${typesDelimitor}`; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /* |
| 44 | + if (svgConstants !== '') { |
| 45 | + const fileContent = (svgConstants += types += generateInterfaceDefinition(interfaceName, typeName)); |
| 46 | + await writeIconsFile(outputDirectory, fileName, fileContent); |
| 47 | + console.log( |
| 48 | + chalk.blue.bold('svg-to-ts:'), |
| 49 | + chalk.green('Icons file successfully generated under'), |
| 50 | + chalk.green.underline(outputDirectory) |
| 51 | + ); |
| 52 | + } |
| 53 | + */ |
| 54 | + } catch (error) { |
| 55 | + console.log(chalk.blue.bold('svg-to-ts:'), chalk.red('Something went wrong', error)); |
| 56 | + } |
| 57 | +}; |
0 commit comments