title: Best way to import SVG icons into a Svelte app
body: <p>I have about 80 custom SVG icons that I'm importing into a Svelte front-end app. Building on <a href="https://github.com/sveltejs/template" rel="noreferrer">https://github.com/sveltejs/template</a>, it's built with Rollup and includes Typescript, Tailwind, and all the modern goodies.</p>
  <p><a href="https://i.stack.imgur.com/fmeUm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fmeUm.png" alt="enter image description here" /></a></p>
  <p>The dilemma is how to add the icons into the app. As SVGs, the icons are short XML text strings that do not exceed 2kB.</p>
  <h2>Option 1: as image assets</h2>
  <ol>
  <li>Upload all the icons as <code>foo.svg</code> into <code>public/assets/icons</code>.</li>
  <li>Create a svelte component <code>&lt;Icon type=&quot;foo' /&gt;</code> that displays an the icon using <code>&lt;img src=&quot;foo.svg&gt;</code>.</li>
  </ol>
  <p>This approach means that the icons are not part of the code.</p>
  <p><strong>Benefits</strong>: icons can be dynamically loaded by frontend code on demand. No need to bundle all icons into app code.</p>
  <p><strong>Cons</strong>: slow page load if there are a lot of new icons, and the browser has to fetch a dozen 1kB files. Deploying the app as a PWA means we need to manually tell it to cache the icons beforehand.</p>
  <h2>Option 2: as part of the app build</h2>
  <ol>
  <li>Use something like <a href="https://github.com/cristovao-trevisan/svelte-icon" rel="noreferrer">https://github.com/cristovao-trevisan/svelte-icon</a> or <a href="https://github.com/codefeathers/rollup-plugin-svelte-svg" rel="noreferrer">https://github.com/codefeathers/rollup-plugin-svelte-svg</a> to directly import each icon into code: <code>import Home from './icons/home.svg';</code></li>
  <li>Create a svelte component that selects the right imported component or SVG string and displays it.</li>
  </ol>
  <p>Here, the icons are bundled as text strings with the app itself.</p>
  <p><strong>Benefits</strong>: Icons are delivered as part of the app bundle. Caching is unnecessary. Possible to dynamically modify some of the icon code e.g. colors, viewBox, etc on load.</p>
  <p><strong>Cons</strong>: It's unnecessary to include all icons in the app to reduce time to first byte. Can't do bundle splitting, etc. without adding more complexity. Makes the rendering slower because Javascript code needs to first turn a string into an SVG instead of just loading an image.</p>
  <h2>Questions</h2>
  <ul>
  <li>It seems that building icons in tthe app is a better way from this analysis, but have I missed something?</li>
  <li>Does the calculus change if the &quot;icons&quot; are detailed images that are 50-100kB instead of the tiny strings here?</li>
  </ul>