Cla*_*dia 27 prerender server-side-rendering svelte netlify-function sveltekit
我最近开始通过 SvelteKit 使用 Svelte,我对这个框架有一些疑问,但我无法在源代码/文档中找到任何直接答案:
如果您需要从外部 API 请求数据,所有服务器端代码(包括端点)都可以访问 fetch。
谢谢!
Ben*_*ann 18
默认情况下,当您第一次访问站点时,页面也会在服务器端呈现。当您导航到后续页面时,它们将在客户端呈现。
适配器仅在生产中使用。如果您竞选npm run dev本地开发,您仍然可以获得 SSR。在生产中,SSR 的运行方式取决于您选择的适配器。生产时需要适配器。adapter-node在 Node 服务器上运行 SSR、adapter-netlify在 Netlify 函数中运行 SSR 等。
有关自定义 Netlify 函数的讨论,请参阅此处:https ://github.com/sveltejs/kit/issues/1249
SSR 也用于页面,但预渲染意味着渲染发生在构建时,而不是访问者访问页面时。有关更多信息,请参阅此建议文档:https ://github.com/sveltejs/kit/pull/1525
小智 7
Pages are SSR when you first visit the site, including all the code in the script tag of your svelte page. However, as you navigate to other pages, the code will be run on the client and the page will be dynamically rendered as Sveltekit makes a single page web app look like it has different pages with the history API.
You can decide which code runs on the server and which runs on the client. If you don't do anything special, Sveltekit and your deployment environment will decide that for you. If you want some code to run only in browser (perhaps it needs to use the window object or need authentication), you can use the browser variable.
import { browser } from '$app/environment';
if (browser) {
// Code that runs only in browser
}
Run Code Online (Sandbox Code Playgroud)
You can also put the code in the onMount function, which will be run when the component first mounts, which only happens in browser.
import { onMount } from 'svelte';
onMount(() => {
// Do stuff
})
Run Code Online (Sandbox Code Playgroud)
If you want SSR, you can put the function in the load function in route/+page.js. One typical use case is for a blog entry that grabs the content from the database and populates and formats the content. If you get to the page from a URL, or refresh page, the code in the load function will be executed on the server. If you navigate to the page from elsewhere in your web app, the code will be run on the client, but it will look like SSR as the UI will refresh only after the load function returns (you won't see loading screen or a blank page). See the official docs for more for more.
import { error } from '@sveltejs/kit';
/** @type {import('./$types').PageLoad} */
export function load({ params }) {
if (params.slug === 'hello-world') {
return {
title: 'Hello world!',
content: 'Welcome to our blog. Lorem ipsum dolor sit amet...'
};
}
throw error(404, 'Not found');
}
Run Code Online (Sandbox Code Playgroud)
I am not very sure about how to use Netlify function, as Ben mentions, you can see the discussion on https://github.com/sveltejs/kit/issues/1249. Although I think that you might be able to implement the same functionality with +page.server.js, and the "Actions" to invoke them.
| 归档时间: |
|
| 查看次数: |
21689 次 |
| 最近记录: |