Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(@astrojs/react): export renderer for easy loading #11234

Merged
merged 7 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/dull-carpets-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@astrojs/react': minor
---

Exposes a `renderer` object from `@astrojs/react/server.js` and `@astrojs/react/server17.js`. This is useful when using the Container API for on-demand pages:

```ts
import type {APIRoute, SSRLoadedRenderer} from "astro";
import { experimental_AstroContainer } from "astro/container";
import { renderer } from '@astrojs/react/server.js';
import Component from "../components/button.jsx"

export const GET: APIRoute = async (ctx) => {
const renderers: SSRLoadedRenderer[] = [renderer];
const container = await experimental_AstroContainer.create({
renderers
});
return await container.renderToResponse(Component);
}
```
42 changes: 22 additions & 20 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2978,27 +2978,29 @@ export interface AstroRenderer {
jsxTransformOptions?: JSXTransformFn;
}

export type SSRLoadedRendererValue = {
check: AsyncRendererComponentFn<boolean>;
renderToStaticMarkup: AsyncRendererComponentFn<{
html: string;
attrs?: Record<string, string>;
}>;
supportsAstroStaticSlot?: boolean;
/**
* If provided, Astro will call this function and inject the returned
* script in the HTML before the first component handled by this renderer.
*
* This feature is needed by some renderers (in particular, by Solid). The
* Solid official hydration script sets up a page-level data structure.
* It is mainly used to transfer data between the server side render phase
* and the browser application state. Solid Components rendered later in
* the HTML may inject tiny scripts into the HTML that call into this
* page-level data structure.
*/
renderHydrationScript?: () => string;
}

export interface SSRLoadedRenderer extends AstroRenderer {
ssr: {
check: AsyncRendererComponentFn<boolean>;
renderToStaticMarkup: AsyncRendererComponentFn<{
html: string;
attrs?: Record<string, string>;
}>;
supportsAstroStaticSlot?: boolean;
/**
* If provided, Astro will call this function and inject the returned
* script in the HTML before the first component handled by this renderer.
*
* This feature is needed by some renderers (in particular, by Solid). The
* Solid official hydration script sets up a page-level data structure.
* It is mainly used to transfer data between the server side render phase
* and the browser application state. Solid Components rendered later in
* the HTML may inject tiny scripts into the HTML that call into this
* page-level data structure.
*/
renderHydrationScript?: () => string;
};
ssr: SSRLoadedRendererValue;
}

export type HookParameters<
Expand Down
27 changes: 26 additions & 1 deletion packages/astro/test/container.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { describe, it, before } from 'node:test';
import { experimental_AstroContainer } from '../dist/container/index.js';
import {
Fragment,
Expand All @@ -12,6 +12,8 @@ import {
renderSlot,
renderTemplate,
} from '../dist/runtime/server/index.js';
import {loadFixture} from "./test-utils.js";
import testAdapter from "./test-adapter.js";

const BaseLayout = createComponent((result, _props, slots) => {
return render`<html>
Expand Down Expand Up @@ -230,3 +232,26 @@ describe('Container', () => {
assert.match(result, /Is open/);
});
});

describe('Container with renderers', () => {
let fixture
let app;
before(async () => {
fixture = await loadFixture({
root: new URL('./fixtures/container-react/', import.meta.url),
output: "server",
adapter: testAdapter()
});
await fixture.build();
app = await fixture.loadTestAdapterApp();
});

it("the endpoint should return the HTML of the React component", async () => {
const request = new Request("https://example.com/api");
const response = await app.render(request)
const html = await response.text()

assert.match(html, /I am a react button/)
})
});

7 changes: 7 additions & 0 deletions packages/astro/test/fixtures/container-react/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import react from '@astrojs/react';
import { defineConfig } from 'astro/config';

// https://astro.build/config
export default defineConfig({
integrations: [react()],
});
12 changes: 12 additions & 0 deletions packages/astro/test/fixtures/container-react/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@test/react-container",
"version": "0.0.0",
"private": true,
"type": "module",
"dependencies": {
"@astrojs/react": "workspace:*",
"astro": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

export default () => {
return <button id="arrow-fn-component">I am a react button</button>;
}
12 changes: 12 additions & 0 deletions packages/astro/test/fixtures/container-react/src/pages/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type {APIRoute, SSRLoadedRenderer} from "astro";
import { experimental_AstroContainer } from "astro/container";
import { renderer } from '@astrojs/react/server.js';
import Component from "../components/button.jsx"

export const GET: APIRoute = async (ctx) => {
const renderers: SSRLoadedRenderer[] = [renderer];
const container = await experimental_AstroContainer.create({
renderers
});
return await container.renderToResponse(Component);
}
8 changes: 8 additions & 0 deletions packages/integrations/react/server-v17.js
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to create a runtime.js entry point, and re-export these values, but rollup has some issues with it. For the time being, this works

Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,11 @@ export default {
renderToStaticMarkup,
supportsAstroStaticSlot: true,
};

export const renderer = {
ssr: {
check,
renderToStaticMarkup,
supportsAstroStaticSlot: true,
}
}
8 changes: 8 additions & 0 deletions packages/integrations/react/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,11 @@ export default {
renderToStaticMarkup,
supportsAstroStaticSlot: true,
};

export const renderer = {
ssr: {
ematipico marked this conversation as resolved.
Show resolved Hide resolved
check,
renderToStaticMarkup,
supportsAstroStaticSlot: true,
}
}
56 changes: 8 additions & 48 deletions packages/integrations/react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import react, { type Options as ViteReactPluginOptions } from '@vitejs/plugin-react';
import type { AstroIntegration, ContainerRenderer } from 'astro';
import { version as ReactVersion } from 'react-dom';
import type { AstroIntegration } from 'astro';
import type * as vite from 'vite';
import {
getReactMajorVersion,
isUnsupportedVersion,
versionsConfig,
type ReactVersionConfig,
type SupportedReactVersion,
} from './version.js';

export type ReactIntegrationOptions = Pick<
ViteReactPluginOptions,
Expand All @@ -12,39 +18,6 @@ export type ReactIntegrationOptions = Pick<

const FAST_REFRESH_PREAMBLE = react.preambleCode;

const versionsConfig = {
17: {
server: '@astrojs/react/server-v17.js',
client: '@astrojs/react/client-v17.js',
externals: ['react-dom/server.js', 'react-dom/client.js'],
},
18: {
server: '@astrojs/react/server.js',
client: '@astrojs/react/client.js',
externals: ['react-dom/server', 'react-dom/client'],
},
19: {
server: '@astrojs/react/server.js',
client: '@astrojs/react/client.js',
externals: ['react-dom/server', 'react-dom/client'],
},
};

type SupportedReactVersion = keyof typeof versionsConfig;
type ReactVersionConfig = (typeof versionsConfig)[SupportedReactVersion];

function getReactMajorVersion(): number {
const matches = /\d+\./.exec(ReactVersion);
if (!matches) {
return NaN;
}
return Number(matches[0]);
}

function isUnsupportedVersion(majorVersion: number) {
return majorVersion < 17 || majorVersion > 19 || Number.isNaN(majorVersion);
}

function getRenderer(reactConfig: ReactVersionConfig) {
return {
name: '@astrojs/react',
Expand All @@ -53,19 +26,6 @@ function getRenderer(reactConfig: ReactVersionConfig) {
};
}

export function getContainerRenderer(): ContainerRenderer {
const majorVersion = getReactMajorVersion();
if (isUnsupportedVersion(majorVersion)) {
throw new Error(`Unsupported React version: ${majorVersion}.`);
}
const versionConfig = versionsConfig[majorVersion as SupportedReactVersion];

return {
name: '@astrojs/react',
serverEntrypoint: versionConfig.server,
};
}

function optionsPlugin(experimentalReactChildren: boolean): vite.Plugin {
const virtualModule = 'astro:react:opts';
const virtualModuleId = '\0' + virtualModule;
Expand Down
34 changes: 34 additions & 0 deletions packages/integrations/react/src/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { version as ReactVersion } from 'react-dom';

export type SupportedReactVersion = keyof typeof versionsConfig;
export type ReactVersionConfig = (typeof versionsConfig)[SupportedReactVersion];

export function getReactMajorVersion(): number {
const matches = /\d+\./.exec(ReactVersion);
if (!matches) {
return NaN;
}
return Number(matches[0]);
}

export function isUnsupportedVersion(majorVersion: number) {
return majorVersion < 17 || majorVersion > 19 || Number.isNaN(majorVersion);
}

export const versionsConfig = {
17: {
server: '@astrojs/react/server-v17.js',
client: '@astrojs/react/client-v17.js',
externals: ['react-dom/server.js', 'react-dom/client.js'],
},
18: {
server: '@astrojs/react/server.js',
client: '@astrojs/react/client.js',
externals: ['react-dom/server', 'react-dom/client'],
},
19: {
server: '@astrojs/react/server.js',
client: '@astrojs/react/client.js',
externals: ['react-dom/server', 'react-dom/client'],
},
};
5 changes: 3 additions & 2 deletions packages/integrations/react/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"extends": "../../../tsconfig.base.json",
"include": ["src"],
"compilerOptions": {
"outDir": "./dist"
}
"outDir": "./dist",
"allowJs": true
},
}
15 changes: 15 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading