首页 > 解决方案 > context="module" 如何在 Svelte 和 Sapper 中工作?

问题描述

当我在从服务器获取数据时使用 Sapper 构建项目时,预加载函数在脚本 context="module" 中声明,如下所示。

<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>

根据文件

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

但是模块首次评估时的含义是什么?

这是否意味着组件首次渲染时?那么就像下面的代码一样,在 onMount 生命周期方法中声明 api fetch 函数不一样吗?

<script>
  onMount(async() => {
    const res = await fetch(`https://reqres.in/api/users?page=1`);
    const json = await res.json();
  })
</script>

标签: sveltesapper

解决方案


考虑一个导出类的常规 JavaScript 模块:

// Component.js

console.log('evaluating module');

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

如果您将该模块导入您的应用程序,该代码将立即运行:

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

现在我们可以用 Svelte 术语来表达:

  • “评估模块”代码是发生在<script context="module">
  • “实例化组件”代码等同于常规<script>标记中发生的情况

推荐阅读