你好!在本文中,我將指導您將 TypeScript 新增至 Remix + Express 樣板專案的步驟。在本教學結束時,您將擁有一個使用 Express 和 Typescript 運行的功能齊全的 Remix 應用程式。您可以在這裡找到最終代碼。
首先,讓我們先從複製官方 Remix Express 入門範本開始:
npx create-remix@latest --template remix-run/remix/templates/express
接下來,安裝 TypeScript 支援所需的附加相依性:
npm install -D esbuild tsx
刪除現有的 server.js 文件,並建立一個名為 server/index.ts 的新文件。
然後,將以下程式碼複製並貼上到 server/index.ts 中:
// server/index.ts import { createRequestHandler } from "@remix-run/express"; import { type ServerBuild } from "@remix-run/node"; import compression from "compression"; import express from "express"; import morgan from "morgan"; const viteDevServer = process.env.NODE_ENV === "production" ? undefined : await import("vite").then((vite) => vite.createServer({ server: { middlewareMode: true }, }) ); const app = express(); app.use(compression()); // http://expressjs.com/en/advanced/best-practice-security.html#at-a-minimum-disable-x-powered-by-header app.disable("x-powered-by"); // handle asset requests if (viteDevServer) { app.use(viteDevServer.middlewares); } else { // Vite fingerprints its assets so we can cache forever. app.use( "/assets", express.static("build/client/assets", { immutable: true, maxAge: "1y" }) ); } // Everything else (like favicon.ico) is cached for an hour. You may want to be // more aggressive with this caching. app.use(express.static("build/client", { maxAge: "1h" })); app.use(morgan("tiny")); async function getBuild() { try { const build = viteDevServer ? await viteDevServer.ssrLoadModule("virtual:remix/server-build") : // @ts-expect-error - the file might not exist yet but it will // eslint-disable-next-line import/no-unresolved await import("../build/server/remix.js"); return { build: build as unknown as ServerBuild, error: null }; } catch (error) { // Catch error and return null to make express happy and avoid an unrecoverable crash console.error("Error creating build:", error); return { error: error, build: null as unknown as ServerBuild }; } } // handle SSR requests app.all( "*", createRequestHandler({ build: async () => { const { error, build } = await getBuild(); if (error) { throw error; } return build; }, }) ); const port = process.env.PORT || 3000; app.listen(port, () => console.log(`Express server listening at http://localhost:${port}`) );
要在 Remix 完成建置後建置 Express 伺服器,請使用下列內容更新您的 vite.config.ts 檔案:
import { vitePlugin as remix } from "@remix-run/dev"; import { defineConfig } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; import esbuild from "esbuild"; export default defineConfig({ plugins: [ remix({ future: { v3_fetcherPersist: true, v3_relativeSplatPath: true, v3_throwAbortReason: true, }, serverBuildFile: 'remix.js', buildEnd: async () => { await esbuild.build({ alias: { "~": "./app" }, outfile: "build/server/index.js", entryPoints: ["server/index.ts"], external: ['./build/server/*'], platform: 'node', format: 'esm', packages: 'external', bundle: true, logLevel: 'info', }).catch((error: unknown) => { console.error('Error building server:', error); process.exit(1); }); } }), tsconfigPaths(), ], });
現在,更新 package.json 中的啟動和開發腳本:
"scripts": { "build": "remix vite:build", "dev": "tsx server/index.ts", "lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .", "start": "cross-env NODE_ENV=production node ./build/server/index.js", "typecheck": "tsc" }
就是這樣!現在您可以像往常一樣繼續編寫 Remix 程式碼。但您可能想知道:為什麼需要此設定?透過使用 Express,每個請求都會經過 Express 伺服器,讓您可以使用 Express 中間件將資料傳遞給 Remix,例如實現身份驗證時的使用者上下文。
在以後的文章中,我將向您展示如何將 Lucia-Auth 添加到此模板? 。
敬請期待! ?
以上是混音 + Express + TS的詳細內容。更多資訊請關注PHP中文網其他相關文章!