Skip to content

Commit

Permalink
Demo: SSR (WIP) with resolving of loaders and using Parcel to transpi…
Browse files Browse the repository at this point in the history
…le app on startup
  • Loading branch information
jhsware committed Dec 23, 2022
1 parent f58698e commit 2cbae82
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 7 deletions.
1 change: 1 addition & 0 deletions demo/inferno-router-demo/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ pwd.txt
lerna-debug.log

dist
distServer
package-lock.json
.parcel-cache
2 changes: 2 additions & 0 deletions demo/inferno-router-demo/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Demo of Inferno-Router

NOTE: Requires Nodejs >=18 (uses `fetch`)

```sh
cd demo/inferno-router-demo
npm i
Expand Down
9 changes: 5 additions & 4 deletions demo/inferno-router-demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
"inferno-animation": "file:../../packages/inferno-animation",
"inferno-router": "file:../../packages/inferno-router",
"inferno-server": "file:../../packages/inferno-server",
"koa":"^2.14.1",
"koa-json-body":"^5.3.0",
"koa-logger":"^3.2.1",
"koa-router":"^12.0.0"
"inferno-create-element": "file:../../packages/inferno-create-element",
"koa": "^2.14.1",
"koa-json-body": "^5.3.0",
"koa-logger": "^3.2.1",
"koa-router": "^12.0.0"
},
"devDependencies": {
"@parcel/packager-ts": "^2.8.1",
Expand Down
8 changes: 6 additions & 2 deletions demo/inferno-router-demo/src/pages/AboutPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import PageTemplate from './PageTemplate';
import { useLoaderData } from 'inferno-router';

import './AboutPage.scss';
import { useLoaderError } from 'inferno-router';

// const env: any = (typeof window === 'undefined' ? process.env : (window as any).__env__)
// const { FRONTEND_BASE_URI } = env

const BACKEND_HOST = 'http://localhost:1234';

interface IProps {
fetchData: any;
}
Expand All @@ -21,7 +24,7 @@ export default class AboutPage extends Component<IProps> {
},
};

const res = await fetch('/api/about', fetchOptions);
const res = await fetch(new URL('/api/about', BACKEND_HOST), fetchOptions);

if (res.ok) {
try {
Expand All @@ -41,12 +44,13 @@ export default class AboutPage extends Component<IProps> {

render(props, state, context) {
const data = useLoaderData(props) as any;
const err = useLoaderError(props) as any;

return (
<PageTemplate>
<article>
<h1>{data?.title}</h1>
<p>{data?.body}</p>
<p>{data?.body || err?.message}</p>
</article>
</PageTemplate>
);
Expand Down
72 changes: 71 additions & 1 deletion demo/inferno-router-demo/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,36 @@ import logger from 'koa-logger';
import koaRouter from 'koa-router'; // koa-router@next
import koaJSONBody from 'koa-json-body';
import { renderToString, resolveLoaders } from 'inferno-server';
import { StaticRouter } from 'inferno-router'
import {Parcel} from '@parcel/core';
import { createElement } from 'inferno-create-element';

const PORT = process.env.PORT || 3000

// Parcel watch subscription and bundle output
let subscription;
let bundles;

let bundler = new Parcel({
entries: './src/App.tsx',
defaultConfig: '@parcel/config-default',
targets: {
default: {
context: 'node',
engines: {
node: ">=18"
},
distDir: "./distServer",
publicUrl: "/", // Should be picked up from environment
}
},
mode: 'development'
});


const app = new koa()
const api = new koaRouter()
const frontend = new koaRouter()

/**
* Logging
Expand Down Expand Up @@ -35,13 +60,58 @@ api.get('/api/about', async (ctx) => {
})
});

frontend.get('/:slug?', async (ctx) => {
const location = ctx.params.slug === undefined ? '/': `/${ctx.params.slug}`;

const pathToAppJs = bundles.find(b => b.name === 'App.js').filePath;
const { appFactory } = require(pathToAppJs)
const app = appFactory();

const initialData = await resolveLoaders(location, app);

const htmlApp = renderToString(createElement(StaticRouter, {
context: {},
location,
initialData,
}, app))

ctx.body = htmlApp;
})


/**
* Mount all the routes for Koa to handle
*/
app.use(api.routes());
app.use(api.allowedMethods());
app.use(frontend.routes());
app.use(frontend.allowedMethods());

// bundler.watch((err, event) => {
// if (err) {
// // fatal error
// throw err;
// }

// if (event.type === 'buildSuccess') {
// bundles = event.bundleGraph.getBundles();
// console.log(`✨ Built ${bundles.length} bundles in ${event.buildTime}ms!`);
// } else if (event.type === 'buildFailure') {
// console.log(event.diagnostics);
// }
// }).then((sub => subscription = sub));

app.listen(PORT, async () => {

// Trigger first transpile
// https://parceljs.org/features/parcel-api/
try {
let {bundleGraph, buildTime} = await bundler.run();
bundles = bundleGraph.getBundles();
console.log(`✨ Built ${bundles.length} bundles in ${buildTime}ms!`);
} catch (err) {
console.log(err.diagnostics);
}

app.listen(PORT, () => {
console.log('Server listening on: ' + PORT)
})

0 comments on commit 2cbae82

Please sign in to comment.