skip to Main Content

bundler: vite

svg

<svg width="current" height="currnet" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.8941 3.0726C13.5536 2.73193 13.1493 2.46169 12.7043 2.27732C12.2593 2.09295 11.7824 1.99805 11.3007 1.99805C10.8191 1.99805 10.3421 2.09295 9.89716 2.27732C9.45219 2.46169 9.0479 2.73193 8.7074 3.0726L8.00073 3.77926L7.29406 3.0726C6.60627 2.3848 5.67342 1.9984 4.70073 1.9984C3.72804 1.9984 2.79519 2.3848 2.1074 3.0726C1.4196 3.76039 1.0332 4.69324 1.0332 5.66593C1.0332 6.63862 1.4196 7.57147 2.1074 8.25926L2.81406 8.96593L8.00073 14.1526L13.1874 8.96593L13.8941 8.25926C14.2347 7.91876 14.505 7.51447 14.6893 7.0695C14.8737 6.62453 14.9686 6.14759 14.9686 5.66593C14.9686 5.18427 14.8737 4.70733 14.6893 4.26236C14.505 3.81739 14.2347 3.4131 13.8941 3.0726Z" fill="current" stroke="current" stroke-width="1.36774" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

LikeButton component

import styled from "styled-components";
import { ReactComponent as Icon } from "@/assets/icons/heart.svg";

const HeartIcon = styled(Icon)`
  width: 16px;
  height: 16px;
  fill: red;
`;
export default function LikeButton() {
  return <HeartIcon />;
}

Test Component

import LikeButton from "@/components/LikeButton/LikeButton";

export default function Test() {
  return <LikeButton />;
}

error message

Uncaught SyntaxError: The requested module '/src/assets/icons/heart.svg?import' does not provide an export named 'ReactComponent' (at LikeButton.jsx:2:10)

question

How do I create an SVG with a styled component? A reference would be appreciated!

I used the vite bundler and also installed the svgr plugin, but I get an error like above.

2

Answers


  1. Not really sure what exactly the problem is, need to see more of the folder structure but with Vite bundler, it is best to put your assets like .svg or .png into the public folder instead of src/assets

    Login or Signup to reply.
  2. Looking at your import syntax (i.e. import { ReactComponent as Icon } from "@/assets/icons/heart.svg";), it seems as though you’re following examples from create-react-app which uses SVGR under the hood to import SVGs. To achieve the same with vite, you can use the vite-plugin-svgr, for example, like so:

    npm install --save-dev vite-plugin-svgr
    

    Then in your vite.config.ts:

    import svgr from 'vite-plugin-svgr';
    
    export default defineConfig({
      // ...
      plugins: [
        svgr(),
        // ...
      ]
      // ...
    })
    

    Following that, you can import SVGs like so:

    import HeartIcon from '@/assets/icons/heart.svg';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search