Preact+HTM
This tutorial will guide you through building a Preact+HTM SSR application from scratch using the Esmx framework. We'll demonstrate how to create a server-side rendered application through a complete example.
Project Structure
First, let's examine the basic project structure:
1.
2├── package.json # Project configuration file defining dependencies and scripts
3├── tsconfig.json # TypeScript configuration file with compilation options
4└── src # Source code directory
5 ├── app.ts # Main application component defining page structure and logic
6 ├── create-app.ts # Application instance factory for initialization
7 ├── entry.client.ts # Client entry file handling browser-side rendering
8 ├── entry.node.ts # Node.js server entry file for dev environment setup
9 └── entry.server.ts # Server entry file handling SSR rendering logic
Project Configuration
package.json
Create the package.json
file to configure project dependencies and scripts:
package.json
1{
2 "name": "ssr-demo-preact-htm",
3 "version": "1.0.0",
4 "type": "module",
5 "private": true,
6 "scripts": {
7 "dev": "esmx dev",
8 "build": "npm run build:dts && npm run build:ssr",
9 "build:ssr": "esmx build",
10 "preview": "esmx preview",
11 "start": "NODE_ENV=production node dist/index.mjs",
12 "build:dts": "tsc --declaration --emitDeclarationOnly --outDir dist/src"
13 },
14 "dependencies": {
15 "@esmx/core": "*"
16 },
17 "devDependencies": {
18 "@esmx/rspack": "*",
19 "@types/node": "22.8.6",
20 "htm": "^3.1.1",
21 "preact": "^10.26.2",
22 "preact-render-to-string": "^6.5.13",
23 "typescript": "^5.2.2"
24 }
25}
After creating the package.json
file, install project dependencies using any of these commands:
1pnpm install
2# or
3yarn install
4# or
5npm install
This will install all required dependencies including Preact, HTM, TypeScript, and SSR-related packages.
tsconfig.json
Create the tsconfig.json
file to configure TypeScript compilation options:
tsconfig.json
1{
2 "compilerOptions": {
3 "isolatedModules": true,
4 "experimentalDecorators": true,
5 "resolveJsonModule": true,
6 "types": [
7 "@types/node"
8 ],
9 "target": "ESNext",
10 "module": "ESNext",
11 "moduleResolution": "node",
12 "strict": true,
13 "skipLibCheck": true,
14 "allowSyntheticDefaultImports": true,
15 "paths": {
16 "ssr-demo-preact-htm/src/*": [
17 "./src/*"
18 ],
19 "ssr-demo-preact-htm/*": [
20 "./*"
21 ]
22 }
23 },
24 "include": [
25 "src"
26 ],
27 "exclude": [
28 "dist"
29 ]
30}
Source Code Structure
app.ts
Create the main application component src/app.ts
using Preact class components with HTM:
src/app.ts
1/**
2 * @file Example component
3 * @description Demonstrates a page title with auto-updating time, showcasing basic Esmx framework functionality
4 */
5
6import { Component } from 'preact';
7import { html } from 'htm/preact';
8
9export default class App extends Component {
10 state = {
11 time: new Date().toISOString()
12 };
13
14 timer: NodeJS.Timeout | null = null;
15
16 componentDidMount() {
17 this.timer = setInterval(() => {
18 this.setState({
19 time: new Date().toISOString()
20 });
21 }, 1000);
22 }
23
24 componentWillUnmount() {
25 if (this.timer) {
26 clearInterval(this.timer);
27 }
28 }
29
30 render() {
31 const { time } = this.state;
32 return html`
33 <div>
34 <h1><a href="https://www.esmnext.com/guide/frameworks/preact-htm.html" target="_blank">Esmx Quick Start</a></h1>
35 <time datetime=${time}>${time}</time>
36 </div>
37 `;
38 }
39}
create-app.ts
Create src/create-app.ts
to handle application instance creation:
src/create-app.ts
1/**
2 * @file Application instance creation
3 * @description Handles creating and configuring application instances
4 */
5
6import type { VNode } from 'preact';
7import { html } from 'htm/preact';
8import App from './app';
9
10export function createApp(): { app: VNode } {
11 const app = html`<${App} />`;
12 return {
13 app
14 };
15}
entry.client.ts
Create the client entry file src/entry.client.ts
:
src/entry.client.ts
1/**
2 * @file Client entry file
3 * @description Handles client-side interaction logic and dynamic updates
4 */
5
6import { render } from 'preact';
7import { createApp } from './create-app';
8
9// Create application instance
10const { app } = createApp();
11
12// Mount application instance
13render(app, document.getElementById('app')!);
entry.node.ts
Create entry.node.ts
to configure the development environment and server startup:
src/entry.node.ts
1/**
2 * @file Node.js server entry file
3 * @description Configures development environment and server startup, providing SSR runtime
4 */
5
6import http from 'node:http';
7import type { EsmxOptions } from '@esmx/core';
8
9export default {
10 /**
11 * Configures development environment application creator
12 * @description Creates and configures Rspack application instance for development builds and HMR
13 * @param esmx Esmx framework instance providing core functionality
14 * @returns Configured Rspack application instance with HMR support
15 */
16 async devApp(esmx) {
17 return import('@esmx/rspack').then((m) =>
18 m.createRspackHtmlApp(esmx, {
19 config(context) {
20 // Custom Rspack compilation configuration can be added here
21 }
22 })
23 );
24 },
25
26 /**
27 * Configures and starts HTTP server
28 * @description Creates HTTP server instance with Esmx middleware for SSR requests
29 * @param esmx Esmx framework instance providing middleware and rendering
30 */
31 async server(esmx) {
32 const server = http.createServer((req, res) => {
33 // Process requests with Esmx middleware
34 esmx.middleware(req, res, async () => {
35 // Perform server-side rendering
36 const rc = await esmx.render({
37 params: { url: req.url }
38 });
39 res.end(rc.html);
40 });
41 });
42
43 server.listen(3000, () => {
44 console.log('Server started: http://localhost:3000');
45 });
46 }
47} satisfies EsmxOptions;
This file serves as the entry point for development environment configuration and server startup, containing two core functions:
devApp
: Creates and configures the Rspack application instance for development with HMR support.
server
: Creates and configures the HTTP server with Esmx middleware for SSR requests.
entry.server.ts
Create the server-side rendering entry file src/entry.server.ts
:
src/entry.server.ts
1/**
2 * @file Server-side rendering entry file
3 * @description Handles SSR workflow, HTML generation and resource injection
4 */
5
6import type { RenderContext } from '@esmx/core';
7import type { VNode } from 'preact';
8import { render } from 'preact-render-to-string';
9import { createApp } from './create-app';
10
11export default async (rc: RenderContext) => {
12 // Create application instance
13 const { app } = createApp();
14
15 // Generate page content using Preact's renderToString
16 const html = render(app);
17
18 // Commit dependency collection to ensure all required resources are loaded
19 await rc.commit();
20
21 // Generate complete HTML structure
22 rc.html = `<!DOCTYPE html>
23<html lang="en">
24<head>
25 ${rc.preload()}
26 <title>Esmx Quick Start</title>
27 ${rc.css()}
28</head>
29<body>
30 <div id="app">${html}</div>
31 ${rc.importmap()}
32 ${rc.moduleEntry()}
33 ${rc.modulePreload()}
34</body>
35</html>
36`;
37};
Running the Project
After completing the file configurations, use these commands to run the project:
- Development mode:
- Build project:
- Production environment:
Congratulations! You've successfully created a Preact+HTM SSR application using the Esmx framework. Visit http://localhost:3000 to see the result.