React Router v7 已發布。 查看文件
@remix-run/serve

Remix 應用程式伺服器

Remix 的設計理念是讓您擁有自己的伺服器,但如果您不想設定伺服器,可以使用 Remix 應用程式伺服器。它是一個生產就緒的基本 Node.js 伺服器,使用 Express 建構。

根據設計,我們不提供自訂 Remix 應用程式伺服器的選項,因為如果您需要自訂底層的 express 伺服器,我們寧願您完全管理伺服器,而不是建立一個抽象層來處理您可能需要的所有自訂設定。如果您發現想要自訂它,應該改用 @remix-run/express 轉接器。

您可以在 packages/remix-serve/cli.ts 中看到底層的 express 伺服器設定。預設情況下,它使用以下 Express 中介軟體(請參閱其文件以了解預設行為)

HOST 環境變數

您可以使用 process.env.HOST 設定 Express 應用程式的主機名稱,該值將在啟動伺服器時傳遞給內部的 app.listen 方法。

HOST=127.0.0.1 npx remix-serve build/index.js
remix-serve <server-build-path>
# e.g.
remix-serve build/index.js

PORT 環境變數

您可以使用環境變數更改伺服器的連接埠。

PORT=4000 npx remix-serve build/index.js

開發環境

根據 process.env.NODE_ENV,伺服器將以開發或生產模式啟動。

server-build-path 需要指向 remix.config.js 中定義的 serverBuildPath

因為只需要將建置成品(build/public/build/)部署到生產環境,所以 remix.config.js 無法保證在生產環境中可用,因此您需要透過此選項告知 Remix 伺服器建置的位置。

在開發中,remix-serve 會確保執行最新的程式碼,方法是針對每個請求清除 require 快取。這對您的程式碼有一些影響,您可能需要注意

  • 模組範圍內的任何值都會被「重置」

    // this will be reset for every request because the module cache was
    // cleared and this will be required brand new
    const cache = new Map();
    
    export async function loader({
      params,
    }: LoaderFunctionArgs) {
      if (cache.has(params.foo)) {
        return json(cache.get(params.foo));
      }
    
      const record = await fakeDb.stuff.find(params.foo);
      cache.set(params.foo, record);
      return json(record);
    }
    

    如果您需要解決方案以在開發中保留快取,您可以在伺服器中設定一個 單例

  • 任何模組副作用都將保留!這可能會導致問題,但無論如何都應該避免。

    import { json } from "@remix-run/node"; // or cloudflare/deno
    
    // this starts running the moment the module is imported
    setInterval(() => {
      console.log(Date.now());
    }, 1000);
    
    export async function loader() {
      // ...
    }
    

    如果您需要以具有這些類型模組副作用的方式編寫程式碼,則應該設定自己的 @remix-run/express 伺服器,並在開發中使用 pm2-dev 或 nodemon 之類的工具來在檔案變更時重新啟動伺服器。

在生產環境中,這不會發生。伺服器啟動後就結束了。

文件和範例的授權條款為 MIT