Skip to content

Instantly share code, notes, and snippets.

@wallw-teal
Last active August 27, 2024 17:06
Show Gist options
  • Save wallw-teal/aee4bc49ee3d0901ec8163e6fcdc5758 to your computer and use it in GitHub Desktop.
Save wallw-teal/aee4bc49ee3d0901ec8163e6fcdc5758 to your computer and use it in GitHub Desktop.
Simple WebComponent for using Lucide icons with HTMX
import { LogIn } from "lucide";
import replaceElement from "lucide/dist/esm/replaceElement.js";
// this is the same as the typical lucide config ...
const config = {
icons: {
LogIn,
// any other icons you want to use here
},
// ... except that this is required as we are skipping the function which
// sets its default value
nameAttr: "data-lucide",
};
class LucideIcon extends HTMLElement {
connectedCallback() {
replaceElement(this, config);
}
}
customElements.define("lucide-icon", LucideIcon);
// use as <lucide-icon data-lucide="log-in" {...anyAttrs}></lucide-icon>
@wallw-teal
Copy link
Author

wallw-teal commented Aug 26, 2024

Problems with base lucide package with a library like HTMX:

  • you need to figure out how to call createIcons() after the DOM is available but before render (mine were kinda flashing in after initial render because I think I had it running on load, which prompted this setup instead)
  • you also need to have HTMX (or whatever other library without a first-class integration) run createIcons() again when it swaps in content.

Reasons I like it:

  • It allows tree shaking of icons
  • It does not require an extra build step to generate a custom icon font (already need a JS step)
  • Super simple
  • Only runs against new icons as they are rendered
  • Only sends each icon once, and avoids sending full SVG in HTML over-the-wire with repeated requests (which might compress well but seemed wasteful)

Potential Cons:

  • Like an icon font, it does send every icon up front in the JS bundle. You could potentially configure your bundle to lazy load them if you really need to mitigate that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment