@svelte-put/inline-svg
solution for inlining SVGs in svelte land
Introduction
Existing solutions for inlining SVGs in svelte land often rely on component, which proves painful when it comes to styling and event handling. This package attempts to achieve a minimal usage api using svelte action .
Build Time Solution
For an alternative solution to statically inline SVG at build time, use @svelte-put/preprocess-inline-svg .
complementary preprocessor: no runtime logics
import { inlineSvg } from '@svelte-put/preprocess-inline-svg/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [inlineSvg(), sveltekit()],
});
preprocess: usage example
<svg inline-src="google/info"></svg>
See more examples & documentation at @svelte-put/preprocess-inline-svg .
Installation
terminal
npm install --save-dev @svelte-put/inline-svg
Quick Start
The Svelte logo SVG on the right is dynamically inlined on load.
Notice in the source code below, only width
(or height
) is needed;
by default inlineSvg
will calculate the other dimension to keep the aspect ratio.
Quick Start
<script>
import { inlineSvg } from '@svelte-put/inline-svg';
export let src = 'https://raw.githubusercontent.com/sveltejs/branding/master/svelte-logo.svg';
</script>
<!-- add attributes and styling as with any other HTML element -->
<svg use:inlineSvg={src} width="100" class="svelte" />
<style>
svg.svelte {
filter: drop-shadow(0 0 0.5rem theme('colors.svelte'));
}
</style>
Attributes & Inner HTML
Attributes provided to the source svg
element will be kept after build
and override existed ones in the inlined SVG.
merging attributes
<svg use:inlineSvg={'...'} width="100" height="100" class="c-icon"></svg>
InnerHTML of the source svg
element will be replaced with the that
from the inlined SVG.
merging attributes
<svg use:inlineSvg={'...'}>anything in here will be replaced</svg>
If you have a use case where it is useful to append/prepend the innerHTML of inlined SVGs rather than replace it, please raise an issue over at github . For now, let's keep things simple.
Customization
Note that inlineSvg
should only be used on svg
elements!
inlineSvg
can take its parameter as either a string or a config object with the following
options
Option
Description
src
(required) the remote URI to fetch SVG from
type: string
autoDimensions
whether to automatically calculate the missing dimension (width / height) to keep the aspect
ratio
type: boolean
default: true
transform
a function to transform the fetched SVG string before inlining
type: (svg: string) => string
default: (svg) => svg
cache
cache policy for use in fetch request
type: Request.cache
default: 'no-cache'