Add preact/compat support to @astrojs/preact (#3712)

* Add preact/compat renderer (likely broken)

Based on the current Preact renderer and the old preact/compat implementation: f892aeb52f/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 <46791833+kevinzunigacuellar@users.noreply.github.com>

Co-authored-by: Nate Moore <nate@astro.build>
Co-authored-by: Nate Moore <natemoo-re@users.noreply.github.com>
Co-authored-by: Kevin Zuniga Cuellar <46791833+kevinzunigacuellar@users.noreply.github.com>
This commit is contained in:
Chris Swithinbank 2022-06-29 17:42:47 +02:00 committed by GitHub
parent 54cd6b8dd1
commit e3fdc9b403
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 392 additions and 33 deletions

View file

@ -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 }),
],
```

View file

@ -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 })],
});

View file

@ -0,0 +1,10 @@
{
"name": "@e2e/preact-component",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/preact": "workspace:*",
"astro": "workspace:*",
"preact": "^10.7.3"
}
}

View file

@ -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;
}

View file

@ -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>
</>
);
}

View file

@ -0,0 +1,5 @@
import React from 'react';
export default function({ id }) {
return <div id={id}>Framework client:only component</div>
}

View file

@ -0,0 +1,4 @@
<html>
<head><title>Preact compat component</title></head>
<body><slot></slot></body>
</html>

View file

@ -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>

View file

@ -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" />

View file

@ -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',
});
});

View file

@ -2,57 +2,80 @@
This **[Astro integration][astro-integration]** enables server-side rendering and client-side hydration for your [Preact](https://preactjs.com/) components.
- <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>
## Why Preact?
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.
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).
**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.
## Installation
There are two ways to add integrations to your project. Let's try the most convenient option first!
<details>
<summary>Quick Install</summary>
<br/>
### `astro add` command
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.
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
```sh
# Using NPM
npx astro add preact
# Using Yarn
yarn astro add preact
# Using PNPM
pnpx astro add preact
```
To install `@astrojs/preact`, run the following from your project directory and follow the prompts:
Then, restart the dev server by typing `CTRL-C` and then `npm run astro dev` in the terminal window that was running Astro.
```sh
# Using NPM
npx astro add preact
# Using Yarn
yarn astro add preact
# Using PNPM
pnpx astro add preact
```
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>
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>Manual Install</summary>
<br/>
### Install dependencies manually
First, install the `@astrojs/preact` package using your package manager. If you're using npm or aren't sure, run this in the terminal:
First, install the `@astrojs/preact` integration like so:
```
npm install @astrojs/preact
```
```
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,
@ -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`, Preacts compatibility layer for rendering React components without needing to install or ship Reacts 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

View file

@ -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": {

View file

@ -1,6 +1,6 @@
import { AstroIntegration } from 'astro';
import { AstroIntegration, AstroRenderer, ViteUserConfig } from 'astro';
function getRenderer() {
function getRenderer(): AstroRenderer {
return {
name: '@astrojs/preact',
clientEntrypoint: '@astrojs/preact/client.js',
@ -18,8 +18,36 @@ function getRenderer() {
};
}
function getViteConfiguration() {
function getCompatRenderer(): AstroRenderer {
return {
name: '@astrojs/preact',
clientEntrypoint: '@astrojs/preact/client.js',
serverEntrypoint: '@astrojs/preact/server.js',
jsxImportSource: 'react',
jsxTransformOptions: async () => {
const {
default: { default: jsx },
// @ts-expect-error types not found
} = await import('@babel/plugin-transform-react-jsx');
return {
plugins: [
jsx({}, { runtime: 'automatic', importSource: 'preact/compat' }),
['babel-plugin-module-resolver', {
alias: {
'react': 'preact/compat',
'react-dom/test-utils': 'preact/test-utils',
'react-dom': 'preact/compat',
'react/jsx-runtime': 'preact/jsx-runtime'
}
}],
],
};
},
};
}
function getViteConfiguration(compat?: boolean): ViteUserConfig {
const viteConfig: ViteUserConfig = {
optimizeDeps: {
include: [
'@astrojs/preact/client.js',
@ -33,16 +61,36 @@ function getViteConfiguration() {
external: ['preact-render-to-string'],
},
};
if (compat) {
viteConfig.optimizeDeps!.include!.push(
'preact/compat',
'preact/test-utils',
'preact/compat/jsx-runtime',
);
viteConfig.resolve = {
alias: [
{ find: 'react', replacement: 'preact/compat' },
{ find: 'react-dom/test-utils', replacement: 'preact/test-utils' },
{ find: 'react-dom', replacement: 'preact/compat' },
{ find: 'react/jsx-runtime', replacement: 'preact/jsx-runtime' }
],
dedupe: ['preact/compat'],
};
}
return viteConfig
}
export default function (): AstroIntegration {
export default function ({ compat }: { compat?: boolean } = {}): AstroIntegration {
return {
name: '@astrojs/preact',
hooks: {
'astro:config:setup': ({ addRenderer, updateConfig }) => {
if (compat) addRenderer(getCompatRenderer());
addRenderer(getRenderer());
updateConfig({
vite: getViteConfiguration(),
vite: getViteConfiguration(compat),
});
},
},

View file

@ -936,6 +936,16 @@ importers:
'@astrojs/react': link:../../../../integrations/react
astro: link:../../..
packages/astro/e2e/fixtures/preact-compat-component:
specifiers:
'@astrojs/preact': workspace:*
astro: workspace:*
preact: ^10.7.3
dependencies:
'@astrojs/preact': link:../../../../integrations/preact
astro: link:../../..
preact: 10.7.3
packages/astro/e2e/fixtures/preact-component:
specifiers:
'@astrojs/preact': workspace:*
@ -1972,10 +1982,12 @@ importers:
'@babel/plugin-transform-react-jsx': ^7.17.12
astro: workspace:*
astro-scripts: workspace:*
babel-plugin-module-resolver: ^4.1.0
preact: ^10.7.3
preact-render-to-string: ^5.2.0
dependencies:
'@babel/plugin-transform-react-jsx': 7.17.12
babel-plugin-module-resolver: 4.1.0
preact-render-to-string: 5.2.0_preact@10.7.3
devDependencies:
astro: link:../../astro
@ -7917,6 +7929,17 @@ packages:
- '@babel/core'
dev: false
/babel-plugin-module-resolver/4.1.0:
resolution: {integrity: sha512-MlX10UDheRr3lb3P0WcaIdtCSRlxdQsB1sBqL7W0raF070bGl1HQQq5K3T2vf2XAYie+ww+5AKC/WrkjRO2knA==}
engines: {node: '>= 8.0.0'}
dependencies:
find-babel-config: 1.2.0
glob: 7.2.0
pkg-up: 3.1.0
reselect: 4.1.6
resolve: 1.22.0
dev: false
/babel-plugin-polyfill-corejs2/0.3.1_@babel+core@7.18.2:
resolution: {integrity: sha512-v7/T6EQcNfVLfcN2X8Lulb7DjprieyLWJK/zOWH5DUYcAgex9sP3h25Q+DLsX9TloXe3y1O8l2q2Jv9q8UVB9w==}
peerDependencies:
@ -8581,6 +8604,11 @@ packages:
/debug/3.2.7:
resolution: {integrity: sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
dependencies:
ms: 2.1.3
dev: false
@ -9501,6 +9529,21 @@ packages:
engines: {node: '>=0.10.0'}
dev: false
/find-babel-config/1.2.0:
resolution: {integrity: sha512-jB2CHJeqy6a820ssiqwrKMeyC6nNdmrcgkKWJWmpoxpE8RKciYJXCcXRq1h2AzCo5I5BJeN2tkGEO3hLTuePRA==}
engines: {node: '>=4.0.0'}
dependencies:
json5: 0.5.1
path-exists: 3.0.0
dev: false
/find-up/3.0.0:
resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==}
engines: {node: '>=6'}
dependencies:
locate-path: 3.0.0
dev: false
/find-up/4.1.0:
resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}
engines: {node: '>=8'}
@ -10563,6 +10606,11 @@ packages:
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
dev: true
/json5/0.5.1:
resolution: {integrity: sha512-4xrs1aW+6N5DalkqSVA8fxh458CXvR99WU8WLKmq4v8eWAL86Xo3BVqyd3SkA9wEVjCMqyvvRRkshAdOnBp5rw==}
hasBin: true
dev: false
/json5/2.2.1:
resolution: {integrity: sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==}
engines: {node: '>=6'}
@ -10686,6 +10734,14 @@ packages:
engines: {node: '>=14'}
dev: true
/locate-path/3.0.0:
resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==}
engines: {node: '>=6'}
dependencies:
p-locate: 3.0.0
path-exists: 3.0.0
dev: false
/locate-path/5.0.0:
resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}
engines: {node: '>=8'}
@ -11462,6 +11518,8 @@ packages:
debug: 3.2.7
iconv-lite: 0.4.24
sax: 1.2.4
transitivePeerDependencies:
- supports-color
dev: false
/netmask/2.0.2:
@ -11545,6 +11603,8 @@ packages:
rimraf: 2.7.1
semver: 5.7.1
tar: 4.4.19
transitivePeerDependencies:
- supports-color
dev: false
/node-releases/2.0.5:
@ -11796,6 +11856,13 @@ packages:
dependencies:
yocto-queue: 0.1.0
/p-locate/3.0.0:
resolution: {integrity: sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==}
engines: {node: '>=6'}
dependencies:
p-limit: 2.3.0
dev: false
/p-locate/4.1.0:
resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}
engines: {node: '>=8'}
@ -11953,6 +12020,11 @@ packages:
/path-browserify/1.0.1:
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
/path-exists/3.0.0:
resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==}
engines: {node: '>=4'}
dev: false
/path-exists/4.0.0:
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'}
@ -12010,6 +12082,13 @@ packages:
dependencies:
find-up: 4.1.0
/pkg-up/3.1.0:
resolution: {integrity: sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==}
engines: {node: '>=8'}
dependencies:
find-up: 3.0.0
dev: false
/playwright-core/1.22.2:
resolution: {integrity: sha512-w/hc/Ld0RM4pmsNeE6aL/fPNWw8BWit2tg+TfqJ3+p59c6s3B6C8mXvXrIPmfQEobkcFDc+4KirNzOQ+uBSP1Q==}
engines: {node: '>=14'}
@ -12917,6 +12996,10 @@ packages:
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
dev: true
/reselect/4.1.6:
resolution: {integrity: sha512-ZovIuXqto7elwnxyXbBtCPo9YFEr3uJqj2rRbcOOog1bmu2Ag85M4hixSwFWyaBMKXNgvPaJ9OSu9SkBPIeJHQ==}
dev: false
/resolve-from/4.0.0:
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
engines: {node: '>=4'}