Below is a full solution for a React project with vite
& svgr
:
# npm
npm install --save-dev vite-plugin-svgr
# yarn
yarn add -D vite-plugin-svgr
# pnpm
pnpm add -D vite-plugin-svgr
Create an svgr template file named svg-template.js
in your root folder, where vote.config
file is at and configure your Vite like so:
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import svgr from "vite-plugin-svgr";
import svgTemplate from "./svg-template";
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
return {
plugins: [
react(),
svgr({
include: "**/*.svg", // allows importing any `svg` file as a React component
svgrOptions: {
template: svgTemplate, // loads the custom svgr template
},
}),
],
...
svg-template.js
:
The aim of the below svgr template is to wrap the imported svg
file with MUI (test on v5) SvgIcon
component so the end result will encapsulate the custom icon within a MUI icon component with all the inherited classes.
// svg-template.js
// https://mcmap.net/q/1040774/-use-custom-svg-file-with-mui-material-ui-icon-component
export default function SvgTemplate(
{ imports, interfaces, componentName, props, jsx, exports },
{ tpl }
) {
return tpl`
import SvgIcon from '@mui/material/SvgIcon';
${imports}
${interfaces}
const ${componentName} = (${props}) => {
return React.createElement(SvgIcon, props, ${jsx.children})
}
${exports}
`;
}
then to use a custom Icon in your React code, simply import an SVG file and use as a compoonent:
import MyIcon from "icons/MyIcon.svg";
const App = () => (
<MyIcon />
)
💡 I advise placing all your icons in one single folder and create an absolute path in your jsconfig
file & bundler's configuration, for easier imports.
References: