Skip to content

Commit

Permalink
Add preact/compat support to @astrojs/preact (withastro#3712)
Browse files Browse the repository at this point in the history
* Add preact/compat renderer (likely broken)

Based on the current Preact renderer and the old preact/compat implementation: https://github.com/withastro/astro/blob/f892aeb52f5a93d81a68d9833eb26bedd06aa2f0/packages/renderers/renderer-preact/compat/index.js

* Make sure name is consistent

* Switch to single integration with compat option

* fix: add module-resolver to alias react => preact/compat

* fix: preact/compat mode

* chore: remove client-compat entrypoint

* chore: add e2e test for preact/compat

* Try to fix frozen lock file error

* Add changeset

* Update README to new structure & document `compat`

* Fix changeset wording

* Fix README typo

* Tweak wording

Co-authored-by: Kevin Zuniga Cuellar <[email protected]>

Co-authored-by: Nate Moore <[email protected]>
Co-authored-by: Nate Moore <[email protected]>
Co-authored-by: Kevin Zuniga Cuellar <[email protected]>
  • Loading branch information
4 people committed Jun 29, 2022
1 parent 54cd6b8 commit e3fdc9b
Show file tree
Hide file tree
Showing 14 changed files with 392 additions and 33 deletions.
13 changes: 13 additions & 0 deletions .changeset/odd-bikes-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@astrojs/preact': minor
---

Add support for enabling `preact/compat` to Preact renderer

To use `preact/compat` to render React components, users can now set `compat` to `true` when using the Preact integration:

```js
integrations: [
preact({ compat: true }),
],
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from 'astro/config';
import preact from '@astrojs/preact';

// https://astro.build/config
export default defineConfig({
integrations: [preact({ compat: true })],
});
10 changes: 10 additions & 0 deletions packages/astro/e2e/fixtures/preact-compat-component/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "@e2e/preact-component",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/preact": "workspace:*",
"astro": "workspace:*",
"preact": "^10.7.3"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.counter {
display: grid;
font-size: 2em;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin-top: 2em;
place-items: center;
}

.counter-message {
text-align: center;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useState } from 'react';
import './Counter.css';

export default function Counter({ children, count: initialCount, id }) {
const [count, setCount] = useState(initialCount);
const add = () => setCount((i) => i + 1);
const subtract = () => setCount((i) => i - 1);

return (
<>
<div id={id} className="counter">
<button className="decrement" onClick={subtract}>-</button>
<pre>{count}</pre>
<button className="increment" onClick={add}>+</button>
</div>
<div className="counter-message">{children}</div>
</>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

export default function({ id }) {
return <div id={id}>Framework client:only component</div>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<html>
<head><title>Preact compat component</title></head>
<body><slot></slot></body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
import Counter from '../components/Counter.jsx';
import PreactCompatComponent from '../components/JSXComponent.jsx';
const someProps = {
count: 0,
};
---

<html>
<head>
<!-- Head Stuff -->
</head>
<body>
<Counter id="server-only" {...someProps}>
<h1>Hello, server!</h1>
</Counter>

<Counter id="client-idle" {...someProps} client:idle>
<h1>Hello, client:idle!</h1>
</Counter>

<Counter id="client-load" {...someProps} client:load>
<h1>Hello, client:load!</h1>
</Counter>

<Counter id="client-visible" {...someProps} client:visible>
<h1>Hello, client:visible!</h1>
</Counter>

<Counter id="client-media" {...someProps} client:media="(max-width: 50em)">
<h1>Hello, client:media!</h1>
</Counter>

<PreactCompatComponent id="client-only" client:only="preact" />
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
layout: ../components/Layout.astro
setup: |
import Counter from '../components/Counter.jsx';
import PreactComponent from '../components/JSXComponent.jsx';
const someProps = {
count: 0,
};
---

<Counter id="server-only" {...someProps}>
# Hello, server!
</Counter>

<Counter id="client-idle" {...someProps} client:idle>
# Hello, client:idle!
</Counter>

<Counter id="client-load" {...someProps} client:load>
# Hello, client:load!
</Counter>

<Counter id="client-visible" {...someProps} client:visible>
# Hello, client:visible!
</Counter>

<Counter id="client-media" {...someProps} client:media="(max-width: 50em)">
# Hello, client:media!
</Counter>

<PreactComponent id="client-only" client:only="preact" />
19 changes: 19 additions & 0 deletions packages/astro/e2e/preact-compat-component.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { prepareTestFactory } from './shared-component-tests.js';

const { test, createTests } = prepareTestFactory({ root: './fixtures/preact-compat-component/' });

test.describe('preact/compat components in Astro files', () => {
createTests({
pageUrl: '/',
pageSourceFilePath: './src/pages/index.astro',
componentFilePath: './src/components/JSXComponent.jsx',
});
});

test.describe('preact/compat components in Markdown files', () => {
createTests({
pageUrl: '/markdown/',
pageSourceFilePath: './src/pages/markdown.md',
componentFilePath: './src/components/JSXComponent.jsx',
});
});
126 changes: 98 additions & 28 deletions packages/integrations/preact/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,57 +2,80 @@

This **[Astro integration][astro-integration]** enables server-side rendering and client-side hydration for your [Preact](https://preactjs.com/) components.

## Installation
- <strong>[Why Preact?](#why-preact)</strong>
- <strong>[Installation](#installation)</strong>
- <strong>[Usage](#usage)</strong>
- <strong>[Configuration](#configuration)</strong>
- <strong>[Examples](#examples)</strong>
- <strong>[Troubleshooting](#troubleshooting)</strong>
- <strong>[Contributing](#contributing)</strong>
- <strong>[Changelog](#changelog)</strong>

There are two ways to add integrations to your project. Let's try the most convenient option first!
## Why Preact?

### `astro add` command
Preact is a library that lets you build interactive UI components for the web. If you want to build interactive features on your site using JavaScript, you may prefer using its component format instead of using browser APIs directly.

Astro includes a CLI tool for adding first party integrations: `astro add`. This command will:
1. (Optionally) Install all necessary dependencies and peer dependencies
2. (Also optionally) Update your `astro.config.*` file to apply this integration
Preact is also a great choice if you have previously used React. Preact provides the same API as React, but in a much smaller 3kB package. It even supports rendering many React components using the `compat` configuration option (see below).

To install `@astrojs/preact`, run the following from your project directory and follow the prompts:
**Want to learn more about Preact before using this integration?**
Check out [“Learn Preact in 10 minutes”](https://preactjs.com/tutorial), an interactive tutorial on their website.

```sh
# Using NPM
npx astro add preact
# Using Yarn
yarn astro add preact
# Using PNPM
pnpx astro add preact
```
## Installation

If you run into any hiccups, [feel free to log an issue on our GitHub](https://github.com/withastro/astro/issues) and try the manual installation steps below.
<details>
<summary>Quick Install</summary>
<br/>

### Install dependencies manually
The `astro add` command-line tool automates the installation for you. Run one of the following commands in a new terminal window. (If you aren't sure which package manager you're using, run the first command.) Then, follow the prompts, and type "y" in the terminal (meaning "yes") for each one.

First, install the `@astrojs/preact` integration like so:
```sh
# Using NPM
npx astro add preact
# Using Yarn
yarn astro add preact
# Using PNPM
pnpx astro add preact
```

```
npm install @astrojs/preact
```
Then, restart the dev server by typing `CTRL-C` and then `npm run astro dev` in the terminal window that was running Astro.

Because this command is new, it might not properly set things up. If that happens, [feel free to log an issue on our GitHub](https://github.com/withastro/astro/issues) and try the manual installation steps below.
</details>

<details>
<summary>Manual Install</summary>
<br/>

First, install the `@astrojs/preact` package using your package manager. If you're using npm or aren't sure, run this in the terminal:

```
npm install @astrojs/preact
```

Most package managers will install associated peer dependencies as well. Still, if you see a "Cannot find package 'preact'" (or similar) warning when you start up Astro, you'll need to install Preact:
```sh
npm install preact
```
```sh
npm install preact
```
Now, apply this integration to your `astro.config.*` file using the `integrations` property:
Then, apply this integration to your `astro.config.*` file using the `integrations` property:
__astro.config.mjs__
```js
import { defineConfig } from 'astro/config';
import preact from '@astrojs/preact';
export default {
export default defineConfig({
// ...
integrations: [preact()],
}
});
```
## Getting started
Finally, restart the dev server.
</details>
## Usage
To use your first Preact component in Astro, head to our [UI framework documentation][astro-ui-frameworks]. You'll explore:
- 📦 how framework components are loaded,
Expand All @@ -61,5 +84,52 @@ To use your first Preact component in Astro, head to our [UI framework documenta

Also check our [Astro Integration Documentation][astro-integration] for more on integrations.

## Configuration

The Astro Preact integration handles how Preact components are rendered and it has its own options. Change these in the `astro.config.mjs` file which is where your project's integration settings live.
For basic usage, you do not need to configure the Preact integration.
<details>
<summary><strong>compat</strong></summary>
You can enable `preact/compat`, Preact’s compatibility layer for rendering React components without needing to install or ship React’s larger libraries to your users’ web browsers.
To do so, pass an object to the Preact integration and set `compat: true`.
```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import preact from '@astrojs/preact';
export default defineConfig({
integrations: [
preact({ compat: true })
],
});
```
With the `compat` option enabled, the Preact integration will render React components as well as Preact components in your project and also allow you to import React components inside Preact components. Read more in [“Switching to Preact (from React)”](https://preactjs.com/guide/v10/switching-to-preact) on the Preact website.
</details>
## Examples
- The [Astro Preact example](https://github.com/withastro/astro/tree/latest/examples/framework-preact) shows how to use an interactive Preact component in an Astro project.
- The [Astro Nanostores example](https://github.com/withastro/astro/tree/latest/examples/with-nanostores) shows how to share state between different components — and even different frameworks! — in an Astro project.
## Troubleshooting
For help, check out the `#support-threads` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
## Contributing
This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for a history of changes to this integration.
[astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
[astro-ui-frameworks]: https://docs.astro.build/en/core-concepts/framework-components/#using-framework-components
1 change: 1 addition & 0 deletions packages/integrations/preact/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
},
"dependencies": {
"@babel/plugin-transform-react-jsx": "^7.17.12",
"babel-plugin-module-resolver": "^4.1.0",
"preact-render-to-string": "^5.2.0"
},
"devDependencies": {
Expand Down
Loading

0 comments on commit e3fdc9b

Please sign in to comment.