Client-Side Rendering

Client-Side Rendering (CSR) is a technical solution that executes page rendering in the browser. In Esmx, when your application cannot deploy a Node.js server instance, you can choose to generate a static index.html file during the build phase to achieve pure client-side rendering.

Use Cases

The following scenarios recommend using client-side rendering:

  • Static Hosting Environments: Such as GitHub Pages, CDN, and other hosting services that do not support server-side rendering
  • Simple Applications: Small applications with low requirements for first-screen loading speed and SEO
  • Development Environments: For quickly previewing and debugging applications during the development phase

Configuration Instructions

HTML Template Configuration

In client-side rendering mode, you need to configure a universal HTML template. This template will serve as the container for your application, including necessary resource references and mounting points.

src/entry.server.ts
1import type { RenderContext } from '@esmx/core';
2
3export default async (rc: RenderContext) => {
4    // Commit dependency collection
5    await rc.commit();
6    
7    // Configure HTML template
8    rc.html = `
9<!DOCTYPE html>
10<html>
11<head>
12    ${rc.preload()}           // Preload resources
13    <title>Esmx</title>
14    ${rc.css()}               // Inject styles
15</head>
16<body>
17    <div id="app"></div>
18    ${rc.importmap()}         // Import map
19    ${rc.moduleEntry()}       // Entry module
20    ${rc.modulePreload()}     // Module preloading
21</body>
22</html>
23`;
24};

Static HTML Generation

To use client-side rendering in a production environment, you need to generate a static HTML file during the build phase. Esmx provides a postBuild hook function to achieve this:

src/entry.node.ts
1import type { EsmxOptions } from '@esmx/core';
2
3export default {
4    async postBuild(esmx) {
5        // Generate static HTML file
6        const rc = await esmx.render();
7        // Write HTML file
8        esmx.writeSync(
9            esmx.resolvePath('dist/client', 'index.html'),
10            rc.html
11        );
12    }
13} satisfies EsmxOptions;