Skip to content

Instantly share code, notes, and snippets.

@Mhdi-kr
Created February 23, 2022 21:33
Show Gist options
  • Save Mhdi-kr/3aca7c6fb7d36d1c732bc30786a12d4e to your computer and use it in GitHub Desktop.
Save Mhdi-kr/3aca7c6fb7d36d1c732bc30786a12d4e to your computer and use it in GitHub Desktop.
script to convert SVG files to optimized Vue components
const fs = require('fs');
const { optimize } = require('svgo');
const { camelCase, toUpper } = require('lodash');
const chalk = require('chalk');
console.log(chalk.green('Loading SVG files from /src/assets/svgs'));
const svgFileNameList = fs.readdirSync('./src/assets/svgs/').filter((item) => item.includes('.svg'));
svgFileNameList.forEach((svgFileName) => {
const path = './src/assets/svgs/' + svgFileName;
const fileNameWithoutExtension = camelCase(svgFileName.split('.')[0]).replace(/^(.)/, toUpper);
try {
console.log(chalk.blueBright('Reading SVG file from ' + path));
const svgContent = fs.readFileSync(path, 'utf-8');
const optimizedSvgContent = optimize(svgContent);
const optimizationRate = parseInt(
((svgContent.length - optimizedSvgContent.data.length) / svgContent.length) * 100
);
const vueTemplate = `<template>${optimizedSvgContent.data}</template><script>export default { name: '${fileNameWithoutExtension}‍' }</script>`;
const outPath = './src/components/svgs/' + fileNameWithoutExtension + '.vue';
console.log(
chalk.blue('Creating component in ' + outPath + ' with over %' + optimizationRate + ' optimization')
);
fs.writeFileSync(outPath, vueTemplate, 'utf-8');
} catch (error) {
console.error(error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment