React Router v7 已发布。 查看文档
运行时、适配器、模板和部署
本页内容

运行时、适配器、模板和部署

部署 Remix 应用程序有四个层次

  1. 一个 JavaScript 运行时,如 Node.js
  2. 一个 JavaScript Web 服务器,如 Express.js
  3. 一个服务器适配器,如 @remix-run/express
  4. 一个 Web 主机或平台

根据您的 Web 主机,您可能层数更少。例如,部署到 Cloudflare Pages 会一次性处理 2、3 和 4。在 Express 应用程序内部部署 Remix 将有全部四层,而使用“Remix 应用服务器”将结合 2 和 3!

您可以自己连接所有这些,也可以从 Remix 模板开始。

让我们来谈谈每个部分的作用。

JavaScript 运行时

Remix 可以部署到任何 JavaScript 运行时,如 Node.js、Shopify Oxygen、Cloudflare Workers/Pages、Fastly Compute、Deno、Bun 等。

每个运行时对 Remix 构建所基于的标准 Web API 的支持程度各不相同,因此需要 Remix 运行时包来 polyfill 运行时中缺失的任何功能。这些 polyfill 包括 Web 标准 API,如 Request、Response、crypto 等。这允许您在服务器上使用与浏览器中相同的 API。

以下运行时包可用

您在应用程序中与之交互的大部分 API 都不是直接从这些包中导入的,因此您的代码在运行时之间具有相当的可移植性。但是,有时您会从这些包中导入某些内容,以获得并非标准 Web API 的特定功能。

例如,您可能希望将 cookie 存储在文件系统或 Cloudflare KV 存储中。这些是运行时特有的功能,与其他运行时不共享

// store sessions in cloudflare KV storage
import { createWorkersKVSessionStorage } from "@remix-run/cloudflare";

// store sessions on the file system in node
import { createFileSessionStorage } from "@remix-run/node";

但如果您将会话存储在 cookie 本身中,则所有运行时都支持此功能

import { createCookieSessionStorage } from "@remix-run/node"; // or cloudflare/deno

适配器

Remix 不是 HTTP 服务器,而是现有 HTTP 服务器内部的处理程序。适配器允许 Remix 处理程序在 HTTP 服务器内部运行。一些 JavaScript 运行时,尤其是 Node.js,有多种创建 HTTP 服务器的方法。例如,在 Node.js 中,您可以使用 Express.js、fastify 或原始 http.createServer

这些服务器中的每一个都有自己的 Request/Response API。适配器的任务是将传入的请求转换为 Web Fetch Request,运行 Remix 处理程序,然后将 Web Fetch Response 适配回宿主服务器的响应 API。

以下是一些伪代码,说明了流程。

// import the app build created by `remix build`
import build from "./build/index.js";

// an express http server
const app = express();

// and here your Remix app is "just a request handler"
app.all("*", createRequestHandler({ build }));

// This is pseudo code, but illustrates what adapters do:
export function createRequestHandler({ build }) {
  // creates a Fetch API request handler from the server build
  const handleRequest = createRemixRequestHandler(build);

  // returns an express.js specific handler for the express server
  return async (req, res) => {
    // adapts the express.req to a Fetch API request
    const request = createRemixRequest(req);

    // calls the app handler and receives a Fetch API response
    const response = await handleRequest(request);

    // adapts the Fetch API response to the express.res
    sendRemixResponse(res, response);
  };
}

Remix 应用服务器

为了方便起见,Remix 应用服务器是新项目、修补或不具有来自 Express 等服务器的任何特定需求且部署到 Node.js 环境的项目的基本 Express 服务器。

请参阅 @remix-run/serve

模板

Remix 的设计具有极大的灵活性,仅具有足够的意见来将 UI 连接到后端,但它不会对您使用的数据库、如何缓存数据或应用程序的部署位置和方式提出意见。

Remix 模板是应用程序开发的起点,其中包含社区创建的所有这些额外意见。

您可以在 Remix CLI 中使用 --template 标志来指向 GitHub 上的存储库,从而使用模板

npx create-remix@latest --template <org>/<repo>

您可以在模板指南中阅读有关模板的更多信息。

一旦你选择了一个模板或从零开始设置了一个应用,你就可以开始构建你的应用了!

文档和示例根据 MIT