Search code examples
javascriptsvgsvelterollup

Is it possible to render SVG elements directly in Svelte?


I am trying to import and render SVG's in Svelte.

I am using @rollup/plugin-url to import the SVG code like so:

<script>
  import arrowCircle from "heroicons/dist/solid-sm/sm-arrow-circle-up.svg"
</script>

<main>
  <object title="Arrow Circle" type="image/svg+xml" data={arrowCircle}></object>
</main>

Now this works (in terms of the SVG content getting brought in) but it renders the following screen:

Rendered SVG

Rendered SVG tag

Ideally I would like to use the <object /> element so I can apply classes to the SVG but given the error I thought I would have a go with the <img /> tag to see if this would at least render the SVG, but instead got this:

<img src="data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22currentColor%22%3E%20%20%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M10%2018a8%208%200%20100-16%208%208%200%20000%2016zm3.707-8.707l-3-3a1%201%200%2000-1.414%200l-3%203a1%201%200%20001.414%201.414L9%209.414V13a1%201%200%20102%200V9.414l1.293%201.293a1%201%200%20001.414-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E">

I also tried just {arrowCircle} but that rendered the above image src as plain text.

From what I can tell it is to do with the data prefix that is part of the raw import.

I am aware of the codefeathers/rollup-plugin-svelte-svg plugin but would like to be able to do be able to do this without another plugin if possible, or at least understand what is going on.

For reference SVG are valid in both <img /> tags as well as <object /> as per this article.


Solution

  • It looks as though the SVG file isn't valid as a standalone image. Try this:

    <?xml version="1.0" encoding="utf-8"?>
    <svg xmlns="http://www.w3.org/2000/svg" ...>...</svg>