分配器作为静态站点生成器 [英] sapper as static site generator

查看:92
本文介绍了分配器作为静态站点生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用sapper作为ssg.当我这样获得数据时:

I would like to use sapper as ssg. When I get data like so:

<script context="module">
export function preload({ params, query }) {
    return this.fetch(`https://jsonplaceholder.typicode.com/posts`)
        .then(r => r.json())
        .then(posts => {
            return {posts} 
        })
}

我可以将站点导出到静态站点.但是在链接上,数据仍然会从jsonplaceholder中获取.仅在重新加载时,数据才会从静态文件夹中获取.如何使所有获取的数据静态?

I can export the site to static. But on links the data still gets fetched from jsonplaceholder. Only on reload the data gets from the static folder. How to get all fetched data static?

推荐答案

因此,一开始可能会造成混淆.要使此工作正常进行,您需要在本地代理您的提取.这是您可以执行的操作:

So this can be a bit confusing in the beginning. To get this working you need to proxy your fetches locally. Here's how you can do that:

/posts/index.json.js中:

let contents;

export function get(req, res) {
    const posts = fetch('do stuff here to fetch')

    contents = JSON.stringify(posts);

    res.writeHead(200, {
        'Content-Type': 'application/json'
    });

    res.end(contents);
}

在您实际的路线组件/posts/index.svelte中:

And in your actual route component /posts/index.svelte:

<script context="module">
    export async function preload({ params, query }) {
        return this.fetch(`index.json`).then(r => r.json()).then(posts => {
            return { posts };
        });
    }
</script>

<script>
export let posts;
</script>

官方 Svelte网站使用此方法获取帖子(从本地文件而不是使用访存).您可能会从中得到一些启发.

The official Svelte website uses this approach to get posts (from a local file rather than using fetch though). You can probably get some inspiration from that.

值得一提的是,preload()函数既被提供给服务器,也被提供给前端,因此您不应在其中放置API密钥.

It is worth mentioning that the preload() function is shipped both to the server and the front-end so you should not put API keys there.

这篇关于分配器作为静态站点生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆