리믹스 + 익스프레스 + TS

WBOY
풀어 주다: 2024-09-10 11:33:44
원래의
482명이 탐색했습니다.

Remix + Express + TS

Remix + Express 프로젝트에 TypeScript를 추가하는 방법

안녕하세요! 이 기사에서는 Remix + Express 상용구 프로젝트에 TypeScript를 추가하는 단계를 안내하겠습니다. 이 튜토리얼이 끝나면 Express 및 Typescript로 실행되는 완전한 기능의 Remix 앱을 갖게 될 것입니다. 여기서 최종 코드를 찾을 수 있습니다.

1단계: 공식 Express Starter 복제

먼저 공식 Remix Express 스타터 템플릿을 복제하는 것부터 시작해 보겠습니다.

npx create-remix@latest --template remix-run/remix/templates/express
로그인 후 복사

2단계: 필수 종속성 추가

다음으로 TypeScript 지원에 필요한 추가 종속성을 설치합니다.

npm install -D esbuild tsx
로그인 후 복사

3단계: TypeScript 서버 파일 생성

기존 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}`)
);

로그인 후 복사

4단계: Vite 구성 업데이트

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(),
  ],
});
로그인 후 복사

5단계: NPM 스크립트 업데이트

이제 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를 추가하는 방법을 보여 드리겠습니다.

계속 지켜봐주세요! ?

위 내용은 리믹스 + 익스프레스 + TS의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!