What is vite-plugin-svgr?
The vite-plugin-svgr package allows you to import SVG files as React components in your Vite projects. This enables you to easily manipulate and use SVG images within your React applications, offering a streamlined workflow for working with SVGs.
What are vite-plugin-svgr's main functionalities?
Import SVG as a React Component
This feature allows you to import an SVG file directly as a React component, which you can then use in your JSX just like any other component. This simplifies the process of using SVGs in your application, making them more flexible and easier to style or manipulate.
import { ReactComponent as Logo } from './logo.svg';
function App() {
return (
<div>
<Logo />
</div>
);
}
Customize SVGs with SVGR Options
This feature leverages SVGR options to customize SVGs when they are imported as React components. You can pass props to the SVG component to dynamically change its properties, such as the title, fill color, and more. This adds a layer of flexibility in how SVGs are rendered and used within your application.
import { ReactComponent as Logo } from './logo.svg?svgr';
function App() {
return (
<div>
<Logo title="Logo Title" />
</div>
);
}
Other packages similar to vite-plugin-svgr
@svgr/webpack
Similar to vite-plugin-svgr, @svgr/webpack allows you to import SVGs as React components in projects using Webpack. While vite-plugin-svgr is tailored for Vite projects, @svgr/webpack is designed for those that are built with Webpack, offering similar functionalities in terms of importing and customizing SVGs.
react-svg-loader
react-svg-loader provides functionality similar to vite-plugin-svgr by allowing SVGs to be imported as React components. However, it is another tool that integrates with Webpack. The main difference lies in the implementation and configuration specifics, with react-svg-loader offering its own set of options and features for handling SVGs in React projects.
vite-plugin-svgr
Vite plugin to transform SVGs into React components. Uses svgr under the hood.
Installation
npm install --save-dev vite-plugin-svgr
yarn add -D vite-plugin-svgr
pnpm add -D vite-plugin-svgr
Usage
import svgr from "vite-plugin-svgr";
export default {
plugins: [svgr()],
};
Then SVG files can be imported as React components:
import Logo from "./logo.svg?react";
If you are using TypeScript, there is also a declaration helper for better type inference. Add the following to vite-env.d.ts
:
Options
svgr({
svgrOptions: {
},
esbuildOptions: {
},
include: "**/*.svg?react",
exclude: "",
});
If you want to enable SVGO you can install @svgr/plugin-svgo
and use following options to enable and configure it:
svgr({
svgrOptions: {
plugins: ["@svgr/plugin-svgo", "@svgr/plugin-jsx"],
svgoConfig: {
floatPrecision: 2,
},
},
});
License
MIT