From 50aa9cc2617620727232ba981ec2ef55ea6f0029 Mon Sep 17 00:00:00 2001 From: Alex Kirszenberg Date: Wed, 14 Sep 2022 23:31:14 +0200 Subject: [PATCH] Initial support for getStaticProps (vercel/turbo#345) Remaining questions: * Should we have some static analysis for `getStaticProps` instead of looking into exports at runtime? * For now, the output of `getStaticProps` (if defined) will always trump the value passed in as `data`. If we consider `data` to be the cached output of `getStaticProps` (in the future, as this is not yet implemented), this logic should be adapted. --- .../src/server_render/server_renderer.js | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/next-swc/crates/next-core/src/server_render/server_renderer.js b/packages/next-swc/crates/next-core/src/server_render/server_renderer.js index 3b343b81ca..15c08fd8cb 100644 --- a/packages/next-swc/crates/next-core/src/server_render/server_renderer.js +++ b/packages/next-swc/crates/next-core/src/server_render/server_renderer.js @@ -1,6 +1,6 @@ const END_OF_OPERATION = process.argv[2] -import Component from '.' +import Component, * as otherExports from '.' import { renderToString, renderToStaticMarkup } from 'react-dom/server' ;('TURBOPACK { transition: next-client }') import chunkGroup from '.' @@ -9,13 +9,13 @@ process.stdout.write('READY\n') const NEW_LINE = '\n'.charCodeAt(0) let buffer = [] -process.stdin.on('data', (data) => { +process.stdin.on('data', async (data) => { let idx = data.indexOf(NEW_LINE) while (idx >= 0) { buffer.push(data.slice(0, idx)) try { let json = JSON.parse(Buffer.concat(buffer).toString('utf-8')) - let result = operation(json) + let result = await operation(json) console.log(`RESULT=${JSON.stringify(result)}`) } catch (e) { console.log(`ERROR=${JSON.stringify(e.stack)}`) @@ -27,9 +27,21 @@ process.stdin.on('data', (data) => { buffer.push(data) }) -function operation(data) { +async function operation(data) { + let staticProps = data + if ('getStaticProps' in otherExports) { + // TODO(alexkirsz) Pass in `context` as defined in + // https://nextjs.org/docs/api-reference/data-fetching/get-static-props#context-parameter + staticProps = otherExports.getStaticProps({}) + if ('then' in staticProps) { + staticProps = await staticProps + } + } + // TODO capture meta info during rendering - const rendered = { __html: renderToString() } + const rendered = { + __html: renderToString(), + } const urls = chunkGroup.map((p) => `/${p}`) const scripts = urls.filter((url) => url.endsWith('.js')) const styles = urls.filter((url) => url.endsWith('.css')) @@ -48,7 +60,7 @@ function operation(data) { id="__NEXT_DATA__" type="application/json" dangerouslySetInnerHTML={{ - __html: htmlEscapeJsonString(JSON.stringify(data)), + __html: htmlEscapeJsonString(JSON.stringify(staticProps)), }} >