|
| 1 | +import * as React from 'react'; |
| 2 | +import { renderToString } from 'react-dom/server'; |
| 3 | +import { match, RouterContext } from 'react-router'; |
| 4 | +import createMemoryHistory from 'history/lib/createMemoryHistory'; |
| 5 | +import { routes } from './routes'; |
| 6 | + |
| 7 | +// The 'asp-prerender-module' tag helper invokes the following function when the React app is to |
| 8 | +// be prerendered on the server. It runs asynchronously, and issues a callback with the React app's |
| 9 | +// initial HTML and any other state variables. |
| 10 | + |
| 11 | +export default function (params: any): Promise<{ html: string }> { |
| 12 | + return new Promise<{ html: string, globals: { [key: string]: any } }>((resolve, reject) => { |
| 13 | + // Match the incoming request against the list of client-side routes, and reject if there was no match |
| 14 | + match({ routes, location: params.location }, (error, redirectLocation, renderProps: any) => { |
| 15 | + if (error) { |
| 16 | + throw error; |
| 17 | + } |
| 18 | + |
| 19 | + // Build an instance of the application and perform an initial render. |
| 20 | + // This will cause any async tasks (e.g., data access) to begin. |
| 21 | + const history = createMemoryHistory(params.url); |
| 22 | + const app = <RouterContext {...renderProps} />; |
| 23 | + renderToString(app); |
| 24 | + |
| 25 | + // Once the tasks are done, we can perform the final render |
| 26 | + params.domainTasks.then(() => { |
| 27 | + resolve({ |
| 28 | + html: renderToString(app), |
| 29 | + globals: { /* Supply any other JSON-serializable data you want to make available on the client */ } |
| 30 | + }); |
| 31 | + }, reject); // Also propagate any errors back into the host application |
| 32 | + }); |
| 33 | + }); |
| 34 | +} |
0 commit comments