Using SVG files in SvelteKit can be achieved in multiple ways, but there are two common methods: directly using SVG tags within Svelte files, and importing SVG as components. Below, I will detail the configuration steps for both methods.
Method 1: Directly Using SVG Tags in Svelte Files
This is the simplest approach, suitable for cases where SVG code is short or changes infrequently. You simply need to copy the SVG's XML code directly into the HTML section of your Svelte component.
Steps:
- Open your SvelteKit project's corresponding
.sveltefile. - Paste the SVG's XML code directly into the HTML section of the file.
Example:
svelte<script> // You can add JavaScript code here </script> <main> <svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg> </main> <style> /* You can add CSS styles here */ </style>
Method 2: Importing SVG as a Component
If you have numerous SVG files or wish to reuse SVG files across multiple components, importing SVG as a Svelte component is a better choice.
Steps:
- First, save your SVG file as a
.sveltefile, for example,Icon.svelte. - Within this Svelte file, directly write the SVG code.
Icon.svelte Example:
svelte<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <!-- SVG content --> </svg>
Example Usage in Another Svelte Component:
svelte<script> import Icon from './Icon.svelte'; </script> <main> <Icon /> </main>
This allows you to flexibly use SVG files within your SvelteKit project. Additionally, using the component approach enhances code readability and reusability. Above are the two common methods for configuring SVG usage in SvelteKit. Choose the method that best suits your project's specific needs.