Deploy

自定义预设


¥Custom Preset

如果你想使用 Nitro 不支持的提供程序,或者想要修改现有的提供程序,你可以在项目中创建本地自定义预设。

自定义预设是本地文件,其中包含一个预设条目,用于定义构建器配置和运行时入口点。

¥Custom presets are local files that have a preset entry that defines builder configuration and a runtime entry point.

::warning 自定义本地预设支持是一项实验性功能。::

¥::warning Custom local preset support is an experimental feature. ::

示例

¥Example

检查 nitrojs/nitro-preset-starter 以获取现成的模板。

首先,我们必须在本地目录 preset/nitro.config.ts 中定义预设入口点。

¥First, we have to define our preset entry point in a local directory preset/nitro.config.ts

./preset/nitro.config.ts
import type { NitroPreset } from "nitropack";
import { fileURLToPath } from "node:url"

export default <NitroPreset>{
  // extends: "node-server", // You can extend existing presets
  entry: fileURLToPath(new URL("./entry.ts", import.meta.url)),
  hooks: {
    compiled() {
      // ...
    },
  },
};

入口点将由你的服务器或提供商使用,你可以完全自定义其行为。

¥The entry point will be used by your server or provider, and you can fully customize its behavior.

import "#internal/nitro/virtual/polyfill";

const nitroApp = useNitroApp();

export default {
  fetch(request: Request) {
    const url = new URL(request.url);
    return nitroApp.localFetch(url.pathname + url.search, {
      context: {},
      host: url.hostname,
      protocol: url.protocol,
      method: request.method,
      headers: request.headers,
      body: undefined,
    });
  },
};

然后,你可以在 nitro 配置文件中使用自定义预设。

¥Then in your nitro config file, you can use your custom preset.

export default defineNitroConfig({
  preset: "./preset",
});

请直接参考 Nitro 源代码,以便更好地理解预设和入口点。

¥Refer to the Nitro source code directly to have a better understanding of presets and entry points.