On demand

用于在 Deno Deploy 中按需渲染页面的插件

配置参数

routesPath string

The file path to save the routes

Default:
"/_routes.json"
preloadPath string

The file path to save the preloaded modules

Default:
"/_preload.ts"
extraData function

Extra data to pass to the pages

描述

此插件允许按需渲染页面。在某些情况下,它可能很有用:

  • 有些页面包含必须在请求时生成的动态内容。
  • 站点太大,有数千个页面,因此构建需要花费太多时间。

Lume 可以为这些情况按需生成页面。

Important

此插件仅适用于 Deno Deploy

安装

在你的 _config.ts 文件中导入此插件以使用它:

import lume from "lume/mod.ts";
import onDemand from "lume/plugins/on_demand.ts";

const site = lume();

site.use(onDemand(/* Options */));

export default site;

它如何工作?

1. 标记按需页面

首先,你需要配置必须按需渲染的页面。这通过将 ondemand 变量设置为 true 来完成。例如,假设我们要动态渲染主页:

---
layout: layout.vto
title: 这是一个标题
ondemand: true
---

<h1>{{ title }}</h1>

2. _routes.json 文件

当站点构建时,带有 ondemand 变量的页面将被跳过,并生成一个 _routes.json 文件,其中包含一个映射,其中包含每个 URL 的关联页面文件,例如:

{
  "/": "./index.vto"
}

3. _preload.ts 文件

如果你的源文件夹包含任何扩展名为 .ts.tsx.js.jsx.mjs 的文件,则还会创建 _preload.ts 归档文件。如果你的站点托管在 Deno Deploy 上,则此文件非常重要。

Deno Deploy 只能动态导入代码中静态可分析的文件。_preload.ts 文件包含的代码什么也不做,但 Deno Deploy 可以分析并准备按需执行。你可以在 Deno Deploy 的更新日志 中找到更多信息。

4. serve 文件

最后,我们必须使用 onDemand 中间件配置一个 HTTP 服务器。创建文件 serve.ts,Deno Deploy 将使用以下代码:

import site from "./_config.ts";
import Server from "lume/core/server.ts";
import onDemand from "lume/middlewares/on_demand.ts";
import "./_preload.ts";

const server = new Server({
  port: 8000,
  root: site.dest(),
});

server.use(onDemand({ site }));

server.start();

console.log("Listening on http://localhost:8000");

中间件需要我们的 site 实例才能渲染页面。我们可以从 _config.ts 文件中导入它。它还会自动加载 _routes.json 文件,以便知道每个 URL 需要渲染哪个文件。

就这样!_routes.json 文件由构建过程自动重新生成,以确保它与你的更改保持同步。

使用额外数据

如果你想使用动态数据,请使用 extraData 选项,该选项接受一个函数,该函数必须返回一个对象,其中包含要传递给页面的额外数据。例如,假设我们要传递请求 URL 的搜索参数:

import lume from "lume/mod.ts";
import onDemand from "lume/plugins/on_demand.ts";

site.use(onDemand({
  extraData(request: Request) {
    const searchParams = new URL(request.url).searchParams;
    const params = Object.fromEntries(searchParams.entries());

    return {
      params,
    };
  },
}));

export default site;

现在,按需页面将具有带有搜索参数值的 params 键。例如,在 Vento 页面中:

---
layout: layout.vto
ondemand: true
url: /example/
---

Hello {{ params.name }}

URL /example/?name=Óscar 将返回 Hello Óscar

查看示例

你可以查看一个包含两个按需生成页面的站点实时示例。以及包含源代码的仓库