Experimental Astro Vite plugin
@astrojs/vite-plugin-astro lets you use Astro components in any Vite project, without an Astro project around them. Your own server decides what to render: a Hono route, an Express handler, or a worker’s fetch() that renders a component and returns the HTML.
Components work as they do in Astro: scoped styles, <script> tags, and islands of React, Preact, Solid, Svelte, or Vue components that hydrate in the browser.
@astrojs/vite-plugin-astro and @astrojs/runtime are experimental. Their APIs may change in any minor release until they reach 1.0.
Installation
Section titled “Installation”Install the plugin and the runtime:
npm install @astrojs/vite-plugin-astro @astrojs/runtimepnpm add @astrojs/vite-plugin-astro @astrojs/runtimeyarn add @astrojs/vite-plugin-astro @astrojs/runtimeThen add the plugin to your Vite config:
import astro from '@astrojs/vite-plugin-astro';import { defineConfig } from 'vite';
export default defineConfig({ plugins: [astro()],});You can now import .astro files from your server code.
Rendering a component
Section titled “Rendering a component”Import a component in your server code, and render it with renderToResponse() or renderToString() from @astrojs/runtime.
The following example uses a Hono route to render a Page.astro component, with a name prop taken from the URL:
import { renderToResponse } from '@astrojs/runtime';import { Hono } from 'hono';import Page from './components/Page.astro';
const app = new Hono();
app.get('/hello/:name', (c) => renderToResponse(Page, { props: { name: c.req.param('name') } }),);
export default app;Page.astro receives the name prop and can use component props as in any Astro project:
---const { name } = Astro.props;---<html lang="en"> <head> <meta charset="utf-8" /> <title>Hello, {name}</title> </head> <body> <h1>Hello, {name}!</h1> </body></html>
<style> h1 { color: rebeccapurple; }</style>