你好!在本文中,我将指导您完成将 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中文网其他相关文章!