pd4d10 / vite-plugin-svgr

Vite plugin to transform SVGs into React components
MIT License
562 stars 54 forks source link

Issue with Importing SVGs: "Does not provide an export named 'ReactComponent'" #117

Open semihtarik opened 5 months ago

semihtarik commented 5 months ago

I am encountering an issue while trying to import SVG files as React components in my Vite + React + TypeScript project. Despite following the documentation and proper configuration, I receive the following error:

javascript Kodu kopyala Uncaught SyntaxError: The requested module '/src/assets/chute-icon.svg?import' does not provide an export named 'ReactComponent' Here are the steps I followed:

Installed the necessary packages:

vite @vitejs/plugin-react vite-plugin-svgr Updated vite.config.ts:

typescript Kodu kopyala import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import svgr from 'vite-plugin-svgr';

export default defineConfig({ plugins: [ react(), svgr({ svgrOptions: { icon: true, }, }), ], }); Created vite-env.d.ts:

typescript Kodu kopyala /// /// Tried to import the SVG as a React component in CustomIcons.tsx:

typescript Kodu kopyala import React from 'react'; import { ReactComponent as ChuteIcon } from '../assets/chute-icon.svg';

const icons = { chute: ChuteIcon, };

type IconProps = { name: keyof typeof icons; width?: string; height?: string; fill?: string; };

const CustomIcons: React.FC = ({ name, width = '24px', height = '24px', fill = 'currentColor' }) => { const Icon = icons[name];

if (!Icon) { return null; }

return (

); };

export default CustomIcons;

I have ensured that the SVG file paths are correct and that the SVG files contain valid SVG content. Despite this, the error persists.

shuaiqidekaige commented 5 months ago

use .svg?react to resolve it

XindiShang commented 3 months ago

https://github.com/pd4d10/vite-plugin-svgr/issues/92#issuecomment-1733753768 This works for me. Plus, add "vite-plugin-svgr/client" to "types" attribute in your ts.config.json, like this:

image
jeffwhuber commented 2 months ago

Change: import { ReactComponent as ChuteIcon } from '../assets/chute-icon.svg';

to

import ChuteIcon from '../assets/chute-icon.svg?react';

Make sure in vite-env.d.ts you have:

/// <reference types="vite-plugin-svgr/client" />

eduwr commented 2 months ago

Maybe this helps. I created a script to update the imports from the project because we had a lot of files to change.

https://gist.github.com/eduwr/9e305ba412abadaa1f38139b195e0c69