1+ import path from 'node:path' ;
2+ import { serve } from 'reactus' ;
3+ import Koa from 'koa' ;
4+ import Router from '@koa/router' ;
5+ import koaStatic from 'koa-static' ;
6+
7+ async function start ( ) {
8+ const app = new Koa ( ) ;
9+ const router = new Router ( ) ;
10+ const cwd = process . cwd ( ) ;
11+
12+ const engine = serve ( {
13+ cwd,
14+ clientRoute : '/client' ,
15+ pagePath : path . join ( cwd , '.build/pages' ) ,
16+ cssRoute : '/assets'
17+ } ) ;
18+
19+ const assets = koaStatic ( path . join ( cwd , 'public' ) , {
20+ maxage : 31536000 ,
21+ immutable : true ,
22+ } ) ;
23+
24+ // Middleware using koa-static to handle public assets
25+ app . use ( assets ) ;
26+
27+ router . get ( '/' , async ( ctx ) => {
28+ try {
29+ ctx . set ( 'Content-Type' , 'text/html' ) ;
30+ ctx . body = await engine . render ( '@/pages/home' ) ;
31+ } catch ( error ) {
32+ console . error ( 'Error rendering /home:' , error ) ;
33+ ctx . status = 500 ;
34+ ctx . body = 'Internal Server Error' ;
35+ }
36+ } ) ;
37+
38+ router . get ( '/about' , async ( ctx ) => {
39+ try {
40+ ctx . set ( 'Content-Type' , 'text/html' ) ;
41+ ctx . body = await engine . render ( '@/pages/about' ) ;
42+ } catch ( error ) {
43+ console . error ( 'Error rendering /about:' , error ) ;
44+ ctx . status = 500 ;
45+ ctx . body = 'Internal Server Error' ;
46+ }
47+ } ) ;
48+
49+ app . use ( router . routes ( ) ) . use ( router . allowedMethods ( ) ) ;
50+
51+ // Catch-all middleware for 404
52+ app . use ( async ( ctx ) => {
53+ if ( ! ctx . body ) {
54+ ctx . status = 404 ;
55+ ctx . body = 'Not Found.' ;
56+ }
57+ } ) ;
58+
59+
60+ app . listen ( 3000 , ( ) => {
61+ console . log ( 'Server listening at http://localhost:3000' ) ;
62+ } ) ;
63+ }
64+
65+ start ( ) . catch ( e => {
66+ console . error ( e ) ;
67+ process . exit ( 1 ) ;
68+ } ) ;
0 commit comments