|

How to embed HTML Icons in 2022

One recurring problem in webdev is icons.
There are lots of ways to get this wrong.
Often they get imported in some design tool and later exported again. This usually results in very messy svg code.
If the icons are not custom created ones, you could also download the icon library. Importing the whole library as a webfont a lá fontawesome or including hundreds of icons as svg code is a bad idea.
Another approach is to put all the svg files in one place, bundle them together into a spritemap. Then you can reference them with xlink:href, but this is deprecated and bad for styling.
For the best control inlining is the best. This has an ok workflow with templating engines like twig or frameworks like vue. Using an icon multiple times adds the svg code as payload for each use, when compiled to static html.
Wouldn't it be nice to load every icon only once and be able to style it like inline code, while also not using any framework?

It is possible! Thx to the amazing work of iconify and antfu's unplugin/icons.

At first glance this only works with common js frameworks. After digging through the code it turn's out that there is an undocumented option for web components. It also has an example in the repo.

This allow's you to pick your icons from iconify or icones and only import the ones you need. Some JS frameworks even allow auto importing for added comfort. You can also freely mix and match multiple icon libraries!

In summary: This is super easy to configure. And works with literally everything eg. Vite, Webpack, Nuxt, Vue, React, Svelte, WebComponents.

By using the iconify extension for vscode you also get icon previews for better dev experience:
Screenshot-2022-01-05-at-16.04.42