Skip to content

kevmodrome/svelte-preprocessor-fetch

master
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 

svelte-preprocessor-fetch

A preprocessor for Svelte that can be used to fetch data before components are compiled.

Demos

ScreenShot

Installation

yarn add -D svelte-preprocessor-fetch

Usage

With rollup-plugin-svelte

// rollup.config.js
import svelte from 'rollup-plugin-svelte';
import preprocessFetch from 'svelte-preprocessor-fetch'

export default {
  ...,
  plugins: [
    svelte({
      preprocess: preprocessFetch()
    })
  ]
}

In components

Create a function called getStaticProps() in your script tag and do your fetches here. The content of this function must be fully self-container. You can not use any variables from outside or import any packages. It has support for fetch via node-fetch.

The data is available using as data in your component.

<script>
  async function getStaticProps() {
    const query = `{
			continents {
				name
			}
		}`;

    const res = await fetch("https://countries.trevorblades.com/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ query })
    });
    const { data } = await res.json();

    return data;
  }
</script>

<main>
  <h2>Continents:</h2>
  <ul>
    {#each data.continents as { name }}
    <li>
      <h3>{name}</h3>
    </li>
    {/each}
  </ul>
</main>

Caveats

This preprocessor is probably extremely brittle, PRs are welcome to improve it further.

About

A preprocessor for Svelte can be used to fetch data before the component is compiled.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published