Last active
February 6, 2025 11:38
-
-
Save mehmetozguldev/16e3adb1cd4d29e457c934d1ade2f795 to your computer and use it in GitHub Desktop.
Convert svg icons to React (.tsx) components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs-extra"); | |
const path = require("path"); | |
const { transform } = require("@svgr/core"); | |
const srcDir = "./icons"; // Source directory containing SVG files | |
const destDir = "./components"; // Destination directory for TSX files | |
const template = ( | |
{ imports, interfaces, componentName, props, jsx }, | |
{ tpl } | |
) => { | |
return tpl` | |
${imports} | |
import { cn } from '@/lib/utils'; | |
${interfaces} | |
export const ${componentName} = ({ className, ...props }: React.ComponentProps<'svg'>) => ( | |
${jsx} | |
); | |
`; | |
}; | |
const svgrOptions = { | |
typescript: true, | |
template, | |
plugins: ["@svgr/plugin-svgo", "@svgr/plugin-jsx"], | |
svgoConfig: { | |
plugins: [ | |
{ | |
name: "preset-default", | |
params: { | |
overrides: { | |
removeViewBox: false, | |
}, | |
}, | |
}, | |
], | |
}, | |
jsx: { | |
babelConfig: { | |
plugins: [ | |
[ | |
"@svgr/babel-plugin-add-jsx-attribute", | |
{ | |
elements: ["svg"], | |
attributes: [ | |
{ | |
name: "className", | |
value: "cn(className)", | |
spread: false, | |
literal: true, | |
position: "end", | |
}, | |
], | |
}, | |
], | |
], | |
}, | |
}, | |
}; | |
function toPascalCase(str) { | |
return str | |
.split("-") | |
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()) | |
.join(""); | |
} | |
async function convertSvgToTsx() { | |
try { | |
await fs.ensureDir(destDir); | |
const files = await fs.readdir(srcDir); | |
for (const file of files) { | |
if (path.extname(file) === ".svg") { | |
const svgCode = await fs.readFile(path.join(srcDir, file), "utf8"); | |
const baseName = path.basename(file, ".svg"); | |
const componentName = toPascalCase(baseName); | |
const tsxCode = await transform(svgCode, svgrOptions, { | |
componentName, | |
}); | |
await fs.writeFile(path.join(destDir, `${baseName}.tsx`), tsxCode); | |
console.log( | |
`Converted ${file} to ${baseName}.tsx (Component: ${componentName})` | |
); | |
} | |
} | |
console.log("Conversion completed successfully!"); | |
} catch (error) { | |
console.error("An error occurred:", error); | |
} | |
} | |
convertSvgToTsx(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment