diff options
Diffstat (limited to 'docs/src/pages/reference')
-rw-r--r-- | docs/src/pages/reference/api-reference.md | 293 | ||||
-rw-r--r-- | docs/src/pages/reference/builtin-components.md | 70 | ||||
-rw-r--r-- | docs/src/pages/reference/cli-reference.md | 72 | ||||
-rw-r--r-- | docs/src/pages/reference/configuration-reference.md | 80 | ||||
-rw-r--r-- | docs/src/pages/reference/renderer-reference.md | 229 |
5 files changed, 0 insertions, 744 deletions
diff --git a/docs/src/pages/reference/api-reference.md b/docs/src/pages/reference/api-reference.md deleted file mode 100644 index 4722da822..000000000 --- a/docs/src/pages/reference/api-reference.md +++ /dev/null @@ -1,293 +0,0 @@ ---- -layout: ~/layouts/MainLayout.astro -title: API Reference ---- - -## `Astro` global - -The `Astro` global is available in all contexts in `.astro` files. It has the following functions: - -### `Astro.fetchContent()` - -`Astro.fetchContent()` is a way to load local `*.md` files into your static site setup. - -```astro ---- -// ./src/components/my-component.astro -const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md ---- - -<div> -{data.slice(0, 3).map((post) => ( - <article> - <h1>{post.title}</h1> - <p>{post.description}</p> - <a href={post.url}>Read more</a> - </article> -))} -</div> -``` - -`.fetchContent()` only takes one parameter: a relative URL glob of which local files you'd like to import. Currently only `*.md` files are supported. It's synchronous, and returns an array of items of type: - -```js -{ - /** frontmatter from the post.. example frontmatter: - title: '', - tag: '', - date: '', - image: '', - author: '', - description: '', - **/ - astro: { - headers: [], // an array of h1...h6 elements in the markdown file - source: '', // raw source of the markdown file - html: '' // rendered HTML of the markdown file - }, - url: '' // the rendered path - }[] -``` - -### `Astro.request` - -`Astro.request` returns an object with the following properties: - -| Name | Type | Description | -| :------------- | :---- | :---------------------------------------------- | -| `url` | `URL` | The URL of the request being rendered. | -| `canonicalURL` | `URL` | [Canonical URL][canonical] of the current page. | - -### `Astro.resolve()` - -`Astro.resolve()` helps with creating URLs relative to the current Astro file, allowing you to reference files within your `src/` folder. - -Astro _does not_ resolve relative links within HTML, such as images: - -```html -<img src="../images/penguin.png" /> -``` - -The above will be sent to the browser as-is and the browser will resolve it relative to the current **page**. If you want it to be resolved relative to the .astro file you are working in, use `Astro.resolve`: - -```astro -<img src={Astro.resolve('../images/penguin.png')} /> -``` - -### `Astro.site` - -`Astro.site` returns a `URL` made from `buildOptions.site` in your Astro config. If undefined, this will return a URL generated from `localhost`. - -```astro ---- -const path = Astro.site.pathname; ---- - -<h1>Welcome to {path}</h1> -``` - -### `Astro.slots` - -`Astro.slots` returns an object with any slotted regions passed into the current Astro file. - -```js -const { - heading as headingSlot, // true or undefined, based on whether `<* slot="heading">` was used. - default as defaultSlot, // true or undefined, based on whether `<* slot>` or `<* default>` was used. -} = Astro.slots; -``` - -## `getStaticPaths()` - -If a page uses dynamic params in the filename, that component will need to export a `getStaticPaths()` function. - -This function is required because Astro is a static site builder. That means that your entire site is built ahead of time. If Astro doesn't know to generate a page at build time, your users won't see it when they visit your site. - -```astro ---- -export async function getStaticPaths() { - return [ - { params: { /* required */ }, props: { /* optional */ } }, - { params: { ... } }, - { params: { ... } }, - // ... - ]; -} ---- -<!-- Your HTML template here. --> -``` - -The `getStaticPaths()` function should return an array of objects to determine which paths will be pre-rendered by Astro. - -⚠️ The `getStaticPaths()` function executes in its own isolated scope once, before any page loads. Therefore you can't reference anything from its parent scope, other than file imports. The compiler will warn if you break this requirement. - -### `params` - -The `params` key of every returned object tells Astro what routes to build. The returned params must map back to the dynamic parameters and rest parameters defined in your component filepath. - -`params` are encoded into the URL, so only strings are supported as values. The value for each `params` object must match the parameters used in the page name. - -For example, suppose that you have a page at `src/pages/posts/[id].astro`. If you export `getStaticPaths` from this page and return the following for paths: - -```astro ---- -export async function getStaticPaths() { - return [ - { params: { id: '1' } }, - { params: { id: '2' } } - ]; -} -const {id} = Astro.request.params; ---- -<body><h1>{id}</h1></body> -``` - -Then Astro will statically generate `posts/1` and `posts/2` at build time. - -### Data Passing with `props` - -To pass additional data to each generated page, you can also set a `props` value on every returned path object. Unlike `params`, `props` are not encoded into the URL and so aren't limited to only strings. - -For example, suppose that you generate pages based off of data fetched from a remote API. You can pass the full data object to the page component inside of `getStaticPaths`: - -```astro ---- -export async function getStaticPaths() { - const data = await fetch('...').then(response => response.json()); - return data.map((post) => { - return { - params: { id: post.id }, - props: { post } }; - }); -} -const {id} = Astro.request.params; -const {post} = Astro.props; ---- -<body><h1>{id}: {post.name}</h1></body> -``` - -Then Astro will statically generate `posts/1` and `posts/2` at build time using the page component in `pages/posts/[id].astro`. The page can reference this data using `Astro.props`: - -### `paginate()` - -Pagination is a common use-case for websites that Astro natively supports via the `paginate()` function. `paginate()` will automatically generate the array to return from `getStaticPaths()` that creates one URL for every page of the paginated collection. The page number will be passed as a param, and the page data will be passed as a `page` prop. - -```js -export async function getStaticPaths({ paginate }) { - // Load your data with fetch(), Astro.fetchContent(), etc. - const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`); - const result = await response.json(); - const allPokemon = result.results; - // Return a paginated collection of paths for all posts - return paginate(allPokemon, { pageSize: 10 }); -} -// If set up correctly, The page prop now has everything that -// you need to render a single page (see next section). -const { page } = Astro.props; -``` - -`paginate()` assumes a file name of `[page].astro` or `[...page].astro`. The `page` param becomes the page number in your URL: - -- `/posts/[page].astro` would generate the URLs `/posts/1`, `/posts/2`, `/posts/3`, etc. -- `/posts/[...page].astro` would generate the URLs `/posts`, `/posts/2`, `/posts/3`, etc. - -#### The pagination `page` prop - -Pagination will pass a `page` prop to every rendered page that represents a single page of data in the paginated collection. This includes the data that you've paginated (`page.data`) as well as metadata for the page (`page.url`, `page.start`, `page.end`, `page.total`, etc). This metadata is useful for things like a "Next Page" button or a "Showing 1-10 of 100" message. - -| Name | Type | Description | -| :----------------- | :-------------------: | :-------------------------------------------------------------------------------------------------------------------------------- | -| `page.data` | `Array` | Array of data returned from `data()` for the current page. | -| `page.start` | `number` | Index of first item on current page, starting at `0` (e.g. if `pageSize: 25`, this would be `0` on page 1, `25` on page 2, etc.). | -| `page.end` | `number` | Index of last item on current page. | -| `page.size` | `number` | How many items per-page. | -| `page.total` | `number` | The total number of items across all pages. | -| `page.currentPage` | `number` | The current page number, starting with `1`. | -| `page.lastPage` | `number` | The total number of pages. | -| `page.url.current` | `string` | Get the URL of the current page (useful for canonical URLs) | -| `page.url.prev` | `string \| undefined` | Get the URL of the previous page (will be `undefined` if on page 1). | -| `page.url.next` | `string \| undefined` | Get the URL of the next page (will be `undefined` if no more pages). | - -### `rss()` - -RSS feeds are another common use-case that Astro supports natively. Call the `rss()` function to generate an `/rss.xml` feed for your project using the same data that you loaded for this page. This file location can be customized (see below). - -```js -// Example: /src/pages/posts/[...page].astro -// Place this function inside your Astro component script. -export async function getStaticPaths({rss}) { - const allPosts = Astro.fetchContent('../post/*.md'); - const sortedPosts = allPosts.sort((a, b) => new Date(b.date) - new Date(a.date)); - // Generate an RSS feed from this collection - rss({ - // The RSS Feed title, description, and custom metadata. - title: 'Don’s Blog', - description: 'An example blog on Astro', - customData: `<language>en-us</language>`, - // The list of items for your RSS feed, sorted. - items: sortedPosts.map(item => ({ - title: item.title, - description: item.description, - link: item.url, - pubDate: item.date, - })), - // Optional: Customize where the file is written to. - // Defaults to "/rss.xml" - dest: "/my/custom/feed.xml", - }); - // Return a paginated collection of paths for all posts - return [...]; -} -``` - -```ts -// The full type definition for the rss() function argument: -interface RSSArgument { - /** (required) Title of the RSS Feed */ - title: string; - /** (required) Description of the RSS Feed */ - description: string; - /** Specify arbitrary metadata on opening <xml> tag */ - xmlns?: Record<string, string>; - /** Specify custom data in opening of file */ - customData?: string; - /** - * Specify where the RSS xml file should be written. - * Relative to final build directory. Example: '/foo/bar.xml' - * Defaults to '/rss.xml'. - */ - dest?: string; - /** Return data about each item */ - items: { - /** (required) Title of item */ - title: string; - /** (required) Link to item */ - link: string; - /** Publication date of item */ - pubDate?: Date; - /** Item description */ - description?: string; - /** Append some other XML-valid data to this item */ - customData?: string; - }[]; -} -``` - -## `import.meta` - -> In this section we use `[dot]` to mean `.`. This is because of a bug in our build engine that is rewriting `import[dot]meta[dot]env` if we use `.` instead of `[dot]`. - -All ESM modules include a `import.meta` property. Astro adds `import[dot]meta[dot]env` through [Vite](https://vitejs.dev/guide/env-and-mode.html). - -**`import[dot]meta[dot]env[dot]SSR`** can be used to know when rendering on the server. Sometimes you might want different logic, for example a component that should only be rendered in the client: - -```jsx -import { h } from 'preact'; - -export default function () { - // Note: rewrite "[dot]" to "." for this to to work in your project. - return import[dot]meta[dot]env[dot]SSR ? <div class="spinner"></div> : <FancyComponent />; -} -``` - -[canonical]: https://en.wikipedia.org/wiki/Canonical_link_element diff --git a/docs/src/pages/reference/builtin-components.md b/docs/src/pages/reference/builtin-components.md deleted file mode 100644 index d171c9a82..000000000 --- a/docs/src/pages/reference/builtin-components.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -layout: ~/layouts/MainLayout.astro -title: Built-In Components ---- - -Astro includes several builtin components for you to use in your projects. All builtin components are available via `import {} from 'astro/components';`. - -## `<Code />` - -```astro ---- -import { Code } from 'astro/components'; ---- -<!-- Syntax highlight some JavaScript code. --> -<Code code={`const foo = 'bar';`} lang="js" /> -<!-- Optional: customize your theme. --> -<Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" /> -<!-- Optional: Enable word wrapping. --> -<Code code={`const foo = 'bar';`} lang="js" wrap /> -``` - -This component provides syntax highlighting for code blocks at build time (no client-side JavaScript included). The component is powered internally by shiki and it supports all popular [themes](https://github.com/shikijs/shiki/blob/main/docs/themes.md) and [languages](https://github.com/shikijs/shiki/blob/main/docs/languages.md). - -You can also use the `<Prism />` component for syntax highlighting powered by the [Prism](https://prismjs.com/) syntax highlighting library. This is the library that Astro's Markdown uses by default. However, we will be transitioning all usage over to `<Code>` as we move towards our v1.0 release. - -## `<Markdown />` - -```astro ---- -import { Markdown } from 'astro/components'; ---- -<Markdown> - # Markdown syntax is now supported! **Yay!** -</Markdown> -``` - -See our [Markdown Guide](/guides/markdown-content) for more info. - -<!-- TODO: We should move some of the specific component info here. --> - -## `<Prism />` - -```astro ---- -import { Prism } from 'astro/components'; ---- -<Prism lang="js" code={`const foo = 'bar';`} /> -``` - -This component provides language-specific syntax highlighting for code blocks. Since this never changes in the client it makes sense to use an Astro component (it's equally reasonable to use a framework component for this kind of thing; Astro is server-only by default for all frameworks!). - -See the [list of languages supported by Prism](https://prismjs.com/#supported-languages) where you can find a language's corresponding alias. And, you can also display your Astro code blocks with lang="astro"! - -## `<Debug />` - -```astro ---- -import Debug from 'astro/debug'; -const serverObject = { - a: 0, - b: "string", - c: { - nested: "object" - } -} ---- -<Debug {serverObject} /> -``` - -This component provides a way to inspect values on the clientside, without any JavaScript. diff --git a/docs/src/pages/reference/cli-reference.md b/docs/src/pages/reference/cli-reference.md deleted file mode 100644 index 0665b35a0..000000000 --- a/docs/src/pages/reference/cli-reference.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -layout: ~/layouts/MainLayout.astro -title: CLI Reference ---- - -## Commands - -### `astro dev` - -Runs the Astro development server. This starts an HTTP server that responds to requests for pages stored in `src/pages` (or which folder is specified in your [configuration](/reference/configuration-reference)). - -**Flags** - -#### `--port` - -Specifies should port to run on. Defaults to `3000`. - -### `astro build` - -Builds your site for production. - -### `astro preview` - -Start a local static file server to serve your built `dist/` directory. Useful for previewing your static build locally, before deploying it. - -This command is meant for local testing only, and is not designed to be run in production. For help with production hosting, check out our guide on [Deploying an Astro Website](/guides/deploy). - -### `astro check` - -Runs diagnostics (such as type-checking) against your project and reports errors to the console. If any errors are found the process will exit with a code of **1**. - -This command is intended to be used in CI workflows. - -## Global Flags - -### `--config path` - -Specify the path to the config file. Defaults to `astro.config.mjs`. Use this if you use a different name for your configuration file or have your config file in another folder. - -```shell -astro --config config/astro.config.mjs dev -``` - -### `--project-root path` - -Specify the path to the project root. If not specified the current working directory is assumed to be the root. - -The root is used for finding the Astro configuration file. - -```shell -astro --project-root examples/snowpack dev -``` - -### `--reload` - -Clears the cache (dependencies are built within Astro apps). - -### `--verbose` - -Enables verbose logging, which is helpful when debugging an issue. - -### `--silent` - -Enables silent logging, which is helpful for when you don't want to see Astro logs. - -### `--version` - -Print the Astro version number and exit. - -### `--help` - -Print the help message and exit. diff --git a/docs/src/pages/reference/configuration-reference.md b/docs/src/pages/reference/configuration-reference.md deleted file mode 100644 index 7d6cb37e9..000000000 --- a/docs/src/pages/reference/configuration-reference.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -layout: ~/layouts/MainLayout.astro -title: Configuration Reference ---- - -To configure Astro, add an `astro.config.mjs` file to the root of your project. - -```js -export default /** @type {import('astro').AstroUserConfig} */ ({ - // all options are optional; these values are the defaults - projectRoot: './', - public: './public/', - dist: './dist/', - src: './src/', - pages: './pages/', - renderers: [ - '@astrojs/renderer-svelte', - '@astrojs/renderer-vue', - '@astrojs/renderer-react', - '@astrojs/renderer-preact', - ], - vite: {}, -}); -``` - -#### projectRoot - -The `projectRoot` option sets the working directory used by Astro. Astro will resolve all other directory options from this path. - -**Default**: The current working directory. - -#### public - -The `public` option sets the directory used to resolve public assets. Astro does not process any files within this directory. - -**Default**: The `public` directory within the `projectRoot` directory. - -#### dist - -The `dist` option sets the directory used to output the final build of the project. Contents of the `public` directory are also copied into this directory. - -**Default**: The `dist` directory within the `projectRoot` directory. - -#### src - -The `src` option sets the directory used to resolve source files, like `pages`. Astro may process, optimize, and bundle any files in this directory. - -**Default**: The `src` directory within the `projectRoot` directory. - -#### pages - -The `pages` option sets the directory used to resolve pages, relative to the `src` option. - -**Default**: The `pages` directory within the `src` directory. - -#### renderers - -The `renderers` option defines the framework renderers to be used by Astro. - -**Default**: An array of `@astrojs/renderer-svelte`, `@astrojs/renderer-vue`, `@astrojs/renderer-react`, and `@astrojs/renderer-preact`. To assign no renderers at all, you must provide an empty array (`[]`). - -#### buildOptions - -The `buildOptions` option configures how a site is built, including its base URL (`buildOptions.site`), whether it includes a sitemap (`buildOptions.sitemap`), and whether its pages should be files (`path.html`) or directories (`path/index.html`) (`buildOptions.pageUrlFormat`). - -#### devOptions - -The `devOptions` option configures features used during development, including the server hostname (`devOptions.hostname`), the server port (`devOptions.port`), and whether urls should include a trailing slash (`devOptions.trailingSlash`). - -#### vite - -The `vite` option configures the internals of Vite. These options can be explored on [ViteJS.dev](https://vitejs.dev/config/). - -#### markdownOptions - -The `markdownOptions` option assigns options to the Markdown parser. These options can be explored on [GitHub](https://github.com/withastro/astro/blob/latest/packages/astro/src/@types/astro.ts). - ---- - -You can view the entire configuration API on [GitHub](https://github.com/withastro/astro/blob/latest/packages/astro/src/@types/astro.ts). diff --git a/docs/src/pages/reference/renderer-reference.md b/docs/src/pages/reference/renderer-reference.md deleted file mode 100644 index 2b589d8c4..000000000 --- a/docs/src/pages/reference/renderer-reference.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -layout: ~/layouts/MainLayout.astro -title: UI Renderer Reference ---- - -Astro is designed to support your favorite UI frameworks. [React](https://npm.im/@astrojs/renderer-react), [Svelte](https://npm.im/@astrojs/renderer-svelte), [Vue](https://npm.im/@astrojs/renderer-vue), and [Preact](https://npm.im/@astrojs/renderer-preact) are all built-in to Astro and supported out of the box. No configuration is needed to enable these. - -Internally, each framework is supported via a framework **renderer.** A renderer is a type of Astro plugin that adds support for a framework. Some are built-in, but you can also provide your own third-party renderers to add Astro support for new frameworks. - -## What is a renderer? - -A renderer is an NPM package that has two responsibilities: - -1. _render a component to a static string of HTML_ at build time. -2. _rehydrate that HTML to create an interactive component_ on the client. - -Take a look at any one of Astro's built-in [`renderers`](https://github.com/withastro/astro/tree/main/packages/renderers) to see this in action. We'll go into more detail in the following sections. - -## Building Your Own Renderer - -> **Building a renderer?** We'd love for you to contribute renderers for popular frameworks back to the Astro repo. Feel free to open an issue or pull request to discuss. - -A simple renderer only needs a few files: - -``` -/my-custom-renderer/ -├── package.json -├── index.js -├── server.js -└── client.js -``` - -### Package Manifest (`package.json`) - -A renderer should include any framework dependencies as package dependencies. For example, `@astrojs/renderer-react` includes `react` & `react-dom` as dependencies in the `package.json` manifest. - -```js -// package.json -"name": "@astrojs/renderer-react", -"dependencies": { - "react": "^17.0.2", - "react-dom": "^17.0.2" -} -``` - -This means that Astro users don't need to install the UI framework packages themselves. The renderer is the only package that your users will need to install. - -### Renderer Entrypoint (`index.js`) - -The main entrypoint of a renderer is a simple JS file which exports a manifest for the renderer. The required values are `name`, `server`, and `client`. - -Additionally, this entrypoint can define a [Vite config object](https://vitejs.dev/config/) that should be used to load non-JavaScript files. - -```js -import myVitePlugin from 'vite-plugin-myplugin'; - -export default { - name: '@astrojs/renderer-xxx', // the renderer name - client: './client.js', // relative path to the client entrypoint - server: './server.js', // (optional) relative path to the server entrypoint - viteConfig(options = { mode: 'development', command: 'serve' }) { - // (optional) return config object for Vite (https://vitejs.dev/config/) - return { - plugins: [myVitePlugin()], // tip: usually this will depend on a Vite plugin - optimizeDeps: { - include: ['my-client-dep'], // tip: it’s always a good idea to specify any client-side hydration deps here - }, - ssr: { - external: ['my-client-dep/node/server.js'], // tip: use ssr.external in case you encounter code meant only for Node - }, - }; - }, - polyfills: ['./shadow-dom-polyfill.js'], // (optional) scripts that should be injected on the page for the component - hydrationPolyfills: ['./hydrate-framework.js'], // (optional) polyfills that need to run before hydration ever occurs - jsxImportSource: 'preact', // (optional) the name of the library from which JSX is imported ("react", "preact", "solid-js", etc.) - jsxTransformOptions: async (options = { mode: 'development', ssr: true }) => { - // (optional) a function to transform JSX files - const { - default: { default: jsx }, - } = await import('@babel/plugin-transform-react-jsx'); - return { - plugins: [jsx({}, { runtime: 'automatic', importSource: 'preact' })], - }; - }, -}; -``` - -### JSX Support - -Astro is unique in that it allows you to mix multiple types of JSX/TSX files in a single project. It does this by reading the `jsxImportSource` and `jsxTransformOptions` from renderers and transforming a file with [Babel](https://babeljs.io/). - -#### `jsxImportSource` - -This is the name of your library (for example `preact` or `react` or `solid-js`) which, if encountered in a file, will signal to Astro that this renderer should be used. - -Users may also manually define `/** @jsxImportSource preact */` in to ensure that the file is processed by this renderer (if, for example, the file has no imports). - -#### `jsxTransformOptions` - -This is an `async` function that returns information about how to transform matching JSX files with [Babel](https://babeljs.io/). It supports [`plugins`](https://babeljs.io/docs/en/plugins) or [`presets`](https://babeljs.io/docs/en/presets) to be passed directly to Babel. - -> Keep in mind that this transform doesn't need to handle TSX separately from JSX, Astro handles that for you! - -`jsxTransformOptions` receives context about whether it’s running in `development` or `production` mode, as well as whether or not it’s running in SSR or client hydration. These allow you to pass separate Babel configurations for various conditions, like if your files should be compiled differently in SSR mode. - -```ts -export interface JSXTransformOptions { - (context: { - /** "development" or "production" */ - mode: string; - /** True if builder is in SSR mode */ - ssr: boolean; - }) => { - plugins?: any[]; - presets?: any[]; - } -} -``` - -### Server Entrypoint (`server.js`) - -The server entrypoint of a renderer is responsible for checking if a component should use this renderer, and if so, how that component should be rendered to a string of static HTML. - -```js -export default { - // should Component use this renderer? - check(Component, props, childHTML) {}, - // Component => string of static HTML - renderToStaticMarkup(Component, props, childHTML) {}, -}; -``` - -#### `check` - -`check` is a function that determines whether a Component should be "claimed" by this renderer. - -In its simplest form, it can check for the existence of a flag on Object-based components. - -```js -function check(Component) { - return Component.isMyFrameworkComponent; -} -``` - -In more complex scenarios, like when a Component is a `Function` without any flags, you may need to use `try/catch` to attempt a full render. This result is cached so that it only runs once per-component. - -```js -function check(Component, props, childHTML) { - try { - const { html } = renderToStaticMarkup(Component, props, childHTML); - return Boolean(html); - } catch (e) {} - return false; -} -``` - -#### `renderToStaticMarkup` - -`renderToStaticMarkup` is a function that renders a Component to a static string of HTML. There's usually a method exported by frameworks named something like `renderToString`. - -```js -import { h, renderToString } from 'xxx'; - -function renderToStaticMarkup(Component, props, childHTML) { - const html = renderToString(h(Component, { ...props, innerHTML: childHTML })); - return { html }; -} -``` - -Note that `childHTML` is an HTML string representing this component's children. If your framework does not support rendering HTML directly, you are welcome to use a wrapper component. By convention, Astro uses the `astro-fragment` custom element to inject `childHTML` into. Your renderer should use that, too. - -```js -import { h, renderToString } from 'xxx'; - -const Wrapper = ({ value }) => - h('astro-fragment', { dangerouslySetInnerHTML: { __html: value } }); - -function renderToStaticMarkup(Component, props, childHTML) { - const html = renderToString( - h(Component, props, h(Wrapper, { value: childHTML })) - ); - return { html }; -} -``` - -The `renderToStaticMarkup` function also supports `async/await` for render functions that return a `Promise`. - -```js -import { h, renderToString } from 'xxx'; - -async function renderToStaticMarkup(Component, props, childHTML) { - const html = await renderToString( - h(Component, { ...props, innerHTML: childHTML }) - ); - return { html }; -} -``` - -### Client Entrypoint (`client.js`) - -The client entrypoint of a renderer is responsible for rehydrating static HTML (the result of `renderToStaticMarkup`) back into a fully interactive component. Its `default` export should be a `function` which accepts the host element of the Component, an `astro-root` custom element. - -> If your framework supports non-destructive component hydration (as opposed to a destructive `render` method), be sure to use that! Following your framework's Server Side Rendering (SSR) guide should point you in the right direction. - -```js -import { h, hydrate } from 'xxx'; - -export default (element) => { - return (Component, props, childHTML) => { - hydrate(h(Component, { ...props, innerHTML: childHTML }), element); - }; -}; -``` - -Note that `childHTML` is an HTML string representing this component's children. If your framework does not support rendering HTML directly, you should use the same wrapper component you used for the server entrypoint. - -```js -import { h, hydrate } from 'xxx'; -import SharedWrapper from './SharedWrapper.js'; - -export default (element) => { - return (Component, props, childHTML) => { - hydrate( - h(Component, props, h(SharedWrapper, { value: childHTML })), - element - ); - }; -}; -``` |