>  기사  >  웹 프론트엔드  >  Vite 및 React.js를 사용한 서버측 렌더링(SSR) 가이드

Vite 및 React.js를 사용한 서버측 렌더링(SSR) 가이드

王林
王林원래의
2024-08-06 02:35:32765검색

A Guide to Server-Side Rendering (SSR) with Vite and React.js

서버 측 렌더링(SSR)의 개념과 이를 통해 웹 애플리케이션의 사용자 경험을 어떻게 향상시킬 수 있는지 자세히 알아보겠습니다.

서버사이드 렌더링의 개념

사용자가 웹사이트를 방문하면 일반적으로 처음에는 기본 HTML을 받은 다음 JavaScript(예: App.js) 및 CSS(예: style.css)와 같은 추가 자산 로드가 트리거됩니다. 클라이언트 측 렌더링이라고도 하는 이러한 전통적인 접근 방식은 사용자가 의미 있는 콘텐츠를 보기 전에 이러한 리소스가 다운로드되고 실행될 때까지 기다려야 함을 의미합니다. 이러한 지연은 특히 연결 속도가 느리거나 장치를 사용하는 사용자의 경우 최적이 아닌 사용자 경험으로 이어질 수 있습니다.

서버측 렌더링은 사용자의 초기 요청에 대한 응답으로 완전히 렌더링된 HTML 페이지를 보내 이 문제를 해결합니다. 사전 렌더링된 이 HTML에는 완전한 마크업이 포함되어 있어 사용자는 JavaScript가 로드되어 실행될 때까지 기다리지 않고 즉시 콘텐츠를 볼 수 있습니다.

SSR의 주요 이점은 다음과 같습니다.

  • LCP(최대 콘텐츠 포함 페인트) 시간 단축: 서버가 완전한 HTML 문서를 전송하므로 사용자는 콘텐츠를 훨씬 빠르게 볼 수 있습니다.

  • 향상된 SEO: 콘텐츠가 HTML로 쉽게 제공되므로 검색 엔진이 콘텐츠를 더욱 효과적으로 색인화할 수 있습니다.

  • 더 나은 초기 사용자 경험: 사용자는 더 빨리 콘텐츠를 읽고 상호 작용할 수 있어 참여율이 높아집니다.

성능 지표 균형 조정

SSR은 LCP를 줄일 수 있지만 다음 페인트(INP)와의 상호작용 시간을 늘릴 수 있습니다. 이는 페이지가 로드된 후 사용자가 페이지와 상호 작용하는 데 걸리는 시간입니다. 목표는 사용자가 버튼을 클릭하는 등 사이트와 상호 작용하기로 결정할 때 필요한 JavaScript가 백그라운드에 로드되어 상호 작용이 원활하고 원활하게 이루어지도록 하는 것입니다.

SSR을 제대로 구현하지 않으면 사용자가 콘텐츠를 볼 수 있지만 JavaScript가 아직 로드되지 않았기 때문에 콘텐츠와 상호작용할 수 없는 상황이 발생할 수 있습니다. 이는 처음에 전체 페이지가 로드될 때까지 기다리는 것보다 더 실망스러울 수 있습니다. 따라서 SSR이 실제로 사용자 경험을 향상시키고 있는지 확인하기 위해 성능 지표를 지속적으로 모니터링하고 측정하는 것이 중요합니다.

Vite 및 React.js에서 SSR 설정

이를 몇 단계로 나누어 보겠습니다.

  1. ClientApp 구성 요소 생성
  2. index.html 업데이트
  3. ServerApp 구성 요소 생성
  4. 빌드 스크립트 설정
  5. 노드 서버 구성

1. ClientApp 구성 요소 생성

모든 브라우저 관련 기능을 처리할 ClientApp.jsx 파일을 만드는 것부터 시작하겠습니다.

// ClientApp.jsx
import { hydrateRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

여기에서는 React-dom/client에서 hydrateRoot를, React-router-dom에서 BrowserRouter를, 그리고 주요 앱 구성 요소를 가져옵니다.

// ClientApp.jsx
// Hydrate the root element with our app
hydrateRoot(document.getElementById('root'), 
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

우리는 hydrateRoot를 사용하여 클라이언트 측에서 앱을 렌더링하고 루트 요소를 지정하고 앱을 BrowserRouter로 래핑합니다. 이 설정을 사용하면 모든 브라우저별 코드가 여기에 유지됩니다.

다음으로 App.jsx를 수정해야 합니다.

// App.jsx
import React from 'react';

// Exporting the App component
export default function App() {
  return (
    <div>
      <h1>Welcome to My SSR React App!</h1>
    </div>
  );
}

여기에서는 데모용으로 앱 구성요소를 단순하게 유지합니다. 클라이언트와 서버 환경 모두에서 사용할 수 있도록 내보냅니다.

2. index.html 업데이트

다음으로 App.jsx 대신 ClientApp.jsx를 로드하도록 index.html을 업데이트하고 구문 분석 토큰을 ​​추가하여 서버에서 HTML 파일을 분할해야 루트 div의 콘텐츠를 스트리밍할 수 있습니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="./vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
  </head>
  <body>
    <div id="root"><!--not rendered--></div>
    <script type="module" src="./src/ClientApp.jsx"></script>
  </body>
</html>

3. ServerApp 구성 요소 생성

이제 서버측 렌더링 로직을 처리하기 위한 ServerApp.jsx 파일을 생성해 보겠습니다.

// ServerApp.jsx
import { renderToPipeableStream } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';
import App from './App';

// Export a function to render the app
export default function render(url, opts) {
  // Create a stream for server-side rendering
  const stream = renderToPipeableStream(
    <StaticRouter location={url}>
      <App />
    </StaticRouter>,
    opts
  );

  return stream;
}

4. 빌드 스크립트 설정

클라이언트와 서버 번들을 모두 빌드하려면 package.json의 빌드 스크립트를 업데이트해야 합니다.

{
  "scripts": {
    "build:client": "tsc vite build --outDir ../dist/client",
    "build:server": "tsc vite build --outDir ../dist/server --ssr ServerApp.jsx",
    "build": "npm run build:client && npm run build:server",
    "start": "node server.js"
  },
  "type": "module"
}

여기에서는 클라이언트와 서버에 대해 별도의 빌드 스크립트를 정의합니다. build:client 스크립트는 클라이언트 번들을 빌드하는 반면, build:server 스크립트는 ServerApp.jsx를 사용하여 서버 번들을 빌드합니다. 빌드 스크립트는 두 빌드 단계를 모두 실행하고 시작 스크립트는 server.js(다음 단계에서 생성됨)를 사용하여 서버를 실행합니다.

TypeScript를 사용하지 않는 경우 클라이언트 및 서버 빌드에서 tsc를 제거하세요.

5. 노드 서버 구성

마지막으로 server.js에서 Node 서버를 구성해 보겠습니다.

// server.js
import express from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import renderApp from './dist/server/ServerApp.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 3001;

// Read the built HTML file
const html = fs.readFileSync(path.resolve(__dirname, './dist/client/index.html')).toString();
const [head, tail] = html.split('<!--not rendered-->');

const app = express();

// Serve static assets
app.use('/assets', express.static(path.resolve(__dirname, './dist/client/assets')));

// Handle all other routes with server-side rendering
app.use((req, res) => {
  res.write(head);

  const stream = renderApp(req.url, {
    onShellReady() {
      stream.pipe(res);
    },
    onShellError(err) {
      console.error(err);
      res.status(500).send('Internal Server Error');
    },
    onAllReady() {
      res.write(tail);
      res.end();
    },
    onError(err) {
      console.error(err);
    }
  });
});

app.listen(PORT, () => {
  console.log(`Listening on http://localhost:${PORT}`);
});

In this file, we set up an Express server to handle static assets and server-side rendering. We read the built index.html file and split it into head and tail parts. When a request is made, we immediately send the head part, then pipe the stream from renderApp to the response, and finally send the tail part once the stream is complete.

By following these steps, we enable server-side rendering in our React application, providing a faster and more responsive user experience. The client receives a fully rendered page initially, and the JavaScript loads in the background, making the app interactive.

Conclusion

By implementing server-side rendering (SSR) in our React application, we can significantly improve the initial load time and provide a better user experience. The steps involved include creating separate components for client and server rendering, updating our build scripts, and configuring an Express server to handle SSR. This setup ensures that users receive a fully rendered HTML page on the first request, while JavaScript loads in the background, making the application interactive seamlessly. This approach not only enhances the perceived performance but also provides a robust foundation for building performant and scalable React applications.

위 내용은 Vite 및 React.js를 사용한 서버측 렌더링(SSR) 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.