Astro的两种页面渲染模式SSR/SSG
Astro默认为static静态渲染模式,可通过在export default defineConfig({...})中配置output: 'server'为服务端SSR渲染。
从2.5版本开始又引入了混合渲染的模式,配置参数如下:
output: 'hybrid',
experimental: {
hybridOutput: true
},其实就页面本身渲染模式就两种(注意这里是页面,非组件),一种是服务端渲染另一种是静态生成,在不同的output模式下控制的参数也不一样
在output: 'server'模式下,默认全部为SSR模式,如果部分页面需要静态生成则需要在页面顶部加入参数:
export const prerender = true;
这时候需要使用export async function getStaticPaths() {...}配置动态路由等参数。
而在output: 'hybrid'模式恰恰相反,默认全部为static静态生成,动态路由部分都需要getStaticPaths参数来生成静态页面,此时如果需要在页面中开启SSR模式则需要在页面顶部加入参数
export const prerender = false;
最后两端SSR和SSG模式的实现代码差别
/** SSG Mode */
export async function getStaticPaths() {
const response = await fetch(import.meta.env.PUBLIC_DIRECTUS_URL + "/items/articles?fields=slug,category.slug,translations.title,translations.body,date_created&deep[translations][_filter][languages_code][_eq]=" + i18next.language + "&[children][_filter][status][_eq]=published").then((response) => response.json());
let articles = response.data;
//console.log(articles)
for (const [index, article] of Object.entries(articles)) {
articles[index] = {
params: { category: article.category.slug, slug: article.slug },
props: {
article: {
...article,
publish_date: formatRelativeTime(new Date(article.date_created))
}
}
};
}
return articles;
}
const { article } = Astro.props;
/* SSR Mode */
const { category, slug } = Astro.params;
if (!slug) {
return Astro.redirect("/404");
}
const response = await fetch(import.meta.env.PUBLIC_DIRECTUS_URL + "/items/articles?fields=*.*&deep[translations][_filter][languages_code][_eq]=" + i18next.language + "&[children][_filter][status][_eq]=published&filter[slug][_eq]=" + slug + "&limit=1").then((response) => response.json());
const article = response.data[0];
if (article.translations.length === 0) {
return Astro.redirect("/404");
}