Import dynamic text file into svelte?

Viewed 23

I have about 50 text files containing SVG paths that need to be parsed in ParseSvg.svelte.

+page.svelte

<script>
  import ParseSvg from "../components/widgets/ParseSVG.svelte"; 
  let hex = "#c412dd";
  let src = 'w1815'
</script>

<ParseSvg {hex} {src} />

ParseSVG.svelte

Hardcoded works perfectly:

import src from "$lib/svg/w1815.svg?raw";

I've tried:

export let src;

 function getSVGUrl(src) {
        return new URL( /* @vite-ignore */ `/src/lib/svg/${src}.svg?raw`, import.meta.url).href;
      }
    
    
const s = getSVGUrl(src)
  
console.log(s)

Console Log Produces:

file:///src/lib/svg/w1815.svg

Trying this:

const s2 = import(s);

Produces this error:

The above dynamic import cannot be analyzed by Vite.

Please point me in the right direction.

1 Answers

When constructing a URL and just using that, this code will not be processed by Vite at all. For that to work you have to manually include your static assets or (in the case of SvelteKit) put them in the /static directory which is already included.

When doing this you also will not have access to the file contents directly (?raw will do nothing), so if you want to access the contents you first have to load the file, e.g. using fetch.

If you want to use a dynamic import instead, you have to follow certain rules. Vite uses a rollup plugin to support this, which comes with various limitations. One of them is that paths have to be relative, another is that a file extension has to be specified (please see the documentation for the full list so you do not miss anything).

As an example given these files:

+page.svelte
svg.svelte
svg-1.svg
svg-2.svg

The page could use the svg.svelte component to reference one of the SVGs via its suffix:

<script>
    import Svg from './svg.svelte';
</script>
<Svg source="1" />
<Svg source="2" />

Then the component could dynamically import the given file and simply output it as HTML:

<script>
    export let source;
</script>

{#await import(`./svg-${source}.svg?raw`) then { default: svg }}
    <span>{@html svg}</span>
{/await}

(For further processing, the file should be imported in an async function in the script.)

Related