Svelte Kit — Importing SVG as Svelte Component
Hi… Its Farrizal. First of all, I never write about technical stuff before, this is my first time. It’s never too late to start right? Okay, not so much giving an introduction, let’s talk about Svelte first. Svelte just release their repo for SvelteKit(Kit) publicly this week. A lot of people waiting for this (including me, I wait it since early 2021) because I think its really fun to code with. Meanwhile, I’m playing around with Sapper (one of svelte framework that support SSR) to create one of my personal project.
The migration is quite straightforward for me since the API is similar. But Sapper is using Snowpack meanwhile Kit using Vite which is a new stack for me. Even though Vite support almost all rollup plugin out there. Still I need to figure out how to Integrate it. In this case, I’m working on importing SVG as svelte component using `rollup-plugin-svelte-svg` with Kit. I take a few hours to find out how. So I decided to share this and with hope can help anyone who want to do the same thing. Let’s get started!
PS: This is kinda workaround until there is plugin for it. But I’m satisfied with the result so far.
Preparation
pnpm add -D @rollup/plugin-image rollup-plugin-svelte-svg @rollup/pluginutils
- @rollup/plugin-image used to import the svg file
- rollup-plugin-svelte-svg used to tranform imported file to SvelteComponent
The Magic
After installing both library, let plug it on vite.config.js:
import image from "@rollup/plugin-image"
import svelteSVG from "rollup-plugin-svelte-svg";const mode = process.env.NODE_ENV;
const dev = mode === "development";/** @type {import('vite').UserConfig} */
export default {
...
plugins: [
{
...image(),
enforce: "pre",
},
svelteSVG({ dev }),
],
}
It’s done.. Yeay!
Actually I hope it simple as that, but we need to modify the plugin implementation a bit. Thanks for sdwvit for giving a hint.
So the final vite.config.js would be:
Viola!, Now we can import any SVG file on svelte. Example usage:
import Logo from "$assets/vectors/logo.svg";<a href="/" class="self-center w-32 cursor-pointer">
<svelte:component this={Logo} />
</a>
Hopefully this article help. Thanks for reading. Cheers!