Search code examples
svelte

How can I get all files in a directory with svelte?


I want to show all images in a folder, like:

<script>
   let list = /*array of all files in a folder*/;
</script>

{#each list as l}
    <img src={(path_of_l)} alt=""/>
{/each}

How can I get that 'list' and paths of its elements?


Solution

  • When the images are inside your project folder and you're using Vite (or SvelteKit) you can use the Glob Import feature:

    const imageModules = import.meta.glob("../../static/*.jpg");
    
      for (const modulePath in imageModules) {
        imageModules[modulePath]().then(({ default: imageUrl }) => {
          console.log(modulePath, imageUrl);
        });
      }