Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How context="module" works in Svelte and Sapper?

Tags:

svelte

sapper

While I was using Sapper to build a project whenever I fetch data from server, preload function is declared inside of script context="module" like this below.

<script context="module">
  export async function preload(page) {
    return await this.fetch(`https://reqres.in/api/users?page=1`)
    .then(res1 => {
      return res1.json()
    }).then(res2 => {
      return { 
        notices: res2.data,
      }
    })
  }
</script>

According to the document

A <script> tag with a context="module" attribute runs once when the module first evaluates, rather than for each component instance. 

But what is the meaning of when the module first evaluates?

Does it mean that when a component first rendered? then isn't the same that declaring api fetch function inside of onMount lifecycle method just like the code below?

<script>
  onMount(async() => {
    const res = await fetch(`https://reqres.in/api/users?page=1`);
    const json = await res.json();
  })
</script>
like image 478
GoonGamja Avatar asked Jun 04 '20 01:06

GoonGamja


People also ask

What is module context in Svelte?

In this article, you are going to learn about how to use the context module in svelte. In svelte, module context is the way of sharing code from one component to another. Suppose, you are creating an e-commerce application with svelte.

How do I export component Svelte?

Exporting a Svelte component </h1> ); export default GreetMessage; Once you've created your class or functional React component, you must use the export keyword or you can use export default to export that React component. In Svelte, by default it's exported as soon you create your Svelte file!


1 Answers

Consider a regular JavaScript module that exports a class:

// Component.js

console.log('evaluating module');

export class Component {
  constructor() {
    console.log('instantiating component');
  }
}

If you import that module into your app, that code will run immediately:

import { Component } from './Component.js';

// "evaluating module" has already been logged. This will only happen once
// for the entire application, however many modules import Component.js

const component1 = new Component(); // logs "instantiating component"
const component2 = new Component(); // logs "instantiating component" again

Now we can put it in Svelte terms:

  • The 'evaluating module' code is what happens in the <script context="module">
  • The 'instantiating component' code is equivalent to what happens in the regular <script> tag
like image 190
Rich Harris Avatar answered Nov 05 '22 21:11

Rich Harris