Best way to import SVG icons into a Svelte app Best way to import SVG icons into a Svelte app typescript typescript

Best way to import SVG icons into a Svelte app


The following approach has these advantages:

  • One central point to maintain all your icons for your app
  • Reduced network requests for fetching SVG icons
  • Reusable icons throughout the app without having duplicate svg elements

Have a dedicated Icon.svelte component setup like this:

<script>    export let name;    export let width = "1rem";    export let height = "1rem";    export let focusable = false;    let icons = [        {          box: 24,          name: "save",          svg: `<g stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8"/><path d="M7 3v5h8"/></g>`        },        {          box: 32,          name: "trash",          svg: `<path d="M12 12h2v12h-2z" /><path d="M18 12h2v12h-2z" /><path d="M4 6v2h2v20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8h2V6zm4 22V8h16v20z" /><path d="M12 2h8v2h-8z" />`        }    ];    let displayIcon = icons.find((e) => e.name === name);</script><svg  class={$$props.class}  {focusable}  {width}  {height}  viewBox="0 0 {displayIcon.box} {displayIcon.box}">{@html displayIcon.svg}</svg>

You can then use it like so:

<Icon name="trash" class="this-is-optional" />


another way is to use a symbol defs file (ex: icons.svg) in your public folder.then in your code do something like this :

Icon.svelte

<script>    export let name;    export let width = "1.5rem";    export let height = "1.5rem";    export let focusable = false;</script><svg class={$$props.class} {focusable} {width} {height}>    <use href={`/icons.svg#${name}`} /></svg>

icons.svg

<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">    <defs>        <symbol id="icon-warning" viewBox="0 0 20 20">            <path d="M19.511 17.98l-8.907-16.632c-0.124-0.215-0.354-0.348-0.604-0.348s-0.481 0.133-0.604 0.348l-8.906 16.632c-0.121 0.211-0.119 0.471 0.005 0.68 0.125 0.211 0.352 0.34 0.598 0.34h17.814c0.245 0 0.474-0.129 0.598-0.34 0.124-0.209 0.126-0.469 0.006-0.68zM11 17h-2v-2h2v2zM11 13.5h-2v-6.5h2v6.5z">            </path>        </symbol>    </defs></svg>

App.svelte

<Icon name="icon-warning" />

this way you use one http call to load svg file. and then just use the part you need in markup.


You can just change the file extension to .svelte and import an SVG as a normal component.