update
This commit is contained in:
1 parent
2396bbcf12
commit
baa5bc091e
14 files changed
+275
-269
No files matched your search
@@ -0,0 +1,48 @@
|
||||
import path from 'path';
|
||||
|
||||
import { FastifyPluginAsync } from 'fastify';
|
||||
|
||||
export const fastifyRenderRouter: FastifyPluginAsync<{
|
||||
isProduction?: boolean;
|
||||
}> = async (app, { isProduction = false }) => {
|
||||
const vite = await import('vite');
|
||||
const { createPageRenderer } = await import('vite-plugin-ssr');
|
||||
await app.register(import('@fastify/express'));
|
||||
app.register(import('@fastify/compress'), { global: false });
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
|
||||
const viteDevServer = await vite.createServer({
|
||||
root: ROOT,
|
||||
server: { middlewareMode: 'ssr' },
|
||||
});
|
||||
app.use(viteDevServer.middlewares);
|
||||
|
||||
const renderPage = createPageRenderer({
|
||||
viteDevServer,
|
||||
isProduction,
|
||||
root: ROOT,
|
||||
});
|
||||
app.get('*', async (req, res) => {
|
||||
const url = req.raw.url || req.url;
|
||||
const pageContextInit = {
|
||||
url,
|
||||
};
|
||||
const pageContext = await renderPage(pageContextInit);
|
||||
const { httpResponse } = pageContext;
|
||||
if (!httpResponse) return;
|
||||
const { body, statusCode, contentType } = httpResponse;
|
||||
res.status(statusCode).type(contentType).compress(body);
|
||||
});
|
||||
};
|
||||
|
||||
async function main() {
|
||||
const { default: fastify } = await import('fastify');
|
||||
const app = fastify();
|
||||
app.register(fastifyRenderRouter);
|
||||
app.listen(3000);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main();
|
||||
}
|
||||
Reference in new issue
Block a user