Socket
Socket
Sign inDemoInstall

@astrojs/preact

Package Overview
Dependencies
Maintainers
3
Versions
64
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@astrojs/preact - npm Package Compare versions

Comparing version 0.0.0-cloudcannon-fix-20230306211609 to 0.0.0-container-20240524151016

2

dist/client.d.ts

@@ -1,2 +0,2 @@

declare const _default: (element: HTMLElement) => (Component: any, props: Record<string, any>, { default: children, ...slotted }: Record<string, any>) => Promise<void>;
declare const _default: (element: HTMLElement) => (Component: any, props: Record<string, any>, { default: children, ...slotted }: Record<string, any>, { client }: Record<string, string>) => Promise<void>;
export default _default;

@@ -1,7 +0,6 @@

import { h, render } from "preact";
import { h, hydrate, render } from "preact";
import StaticHtml from "./static-html.js";
const sharedSignalMap = /* @__PURE__ */ new Map();
var client_default = (element) => async (Component, props, { default: children, ...slotted }) => {
if (!element.hasAttribute("ssr"))
return;
var client_default = (element) => async (Component, props, { default: children, ...slotted }, { client }) => {
if (!element.hasAttribute("ssr")) return;
for (const [key, value] of Object.entries(slotted)) {

@@ -22,17 +21,8 @@ props[key] = h(StaticHtml, { value, name: key });

}
function Wrapper({ children: children2 }) {
let attrs = Object.fromEntries(
Array.from(element.attributes).map((attr) => [attr.name, attr.value])
);
return h(element.localName, attrs, children2);
}
render(
h(
Wrapper,
null,
h(Component, props, children != null ? h(StaticHtml, { value: children }) : children)
),
element.parentNode,
const bootstrap = client !== "only" ? hydrate : render;
bootstrap(
h(Component, props, children != null ? h(StaticHtml, { value: children }) : children),
element
);
element.addEventListener("astro:unmount", () => render(null, element), { once: true });
};

@@ -39,0 +29,0 @@ export {

@@ -1,3 +0,3 @@

import type { PropNameToSignalMap, RendererContext, SignalLike } from './types';
export declare type Context = {
import type { PropNameToSignalMap, RendererContext, SignalLike } from './types.js';
export type Context = {
id: string;

@@ -4,0 +4,0 @@ c: number;

@@ -1,4 +0,8 @@

import { AstroIntegration } from 'astro';
export default function ({ compat }?: {
import { type PreactPluginOptions as VitePreactPluginOptions } from '@preact/preset-vite';
import type { AstroIntegration, ContainerRenderer } from 'astro';
export declare function getContainerRenderer(): ContainerRenderer;
export interface Options extends Pick<VitePreactPluginOptions, 'include' | 'exclude'> {
compat?: boolean;
}): AstroIntegration;
devtools?: boolean;
}
export default function ({ include, exclude, compat, devtools }?: Options): AstroIntegration;

@@ -0,1 +1,4 @@

import { fileURLToPath } from "node:url";
import { preact } from "@preact/preset-vite";
const babelCwd = new URL("../", import.meta.url);
function getRenderer(development) {

@@ -5,83 +8,51 @@ return {

clientEntrypoint: development ? "@astrojs/preact/client-dev.js" : "@astrojs/preact/client.js",
serverEntrypoint: "@astrojs/preact/server.js",
jsxImportSource: "preact",
jsxTransformOptions: async () => {
const {
default: { default: jsx }
} = await import("@babel/plugin-transform-react-jsx");
return {
plugins: [jsx({}, { runtime: "automatic", importSource: "preact" })]
};
}
serverEntrypoint: "@astrojs/preact/server.js"
};
}
function getCompatRenderer(development) {
function getContainerRenderer() {
return {
name: "@astrojs/preact",
clientEntrypoint: development ? "@astrojs/preact/client-dev.js" : "@astrojs/preact/client.js",
serverEntrypoint: "@astrojs/preact/server.js",
jsxImportSource: "react",
jsxTransformOptions: async () => {
const {
default: { default: jsx }
} = 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"
}
}
]
]
};
}
serverEntrypoint: "@astrojs/preact/server.js"
};
}
function getViteConfiguration(compat) {
const viteConfig = {
optimizeDeps: {
include: ["@astrojs/preact/client.js", "preact", "preact/jsx-runtime"],
exclude: ["@astrojs/preact/server.js"]
}
};
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", "preact"]
};
viteConfig.ssr = {
noExternal: ["react", "react-dom", "react-dom/test-utils", "react/jsx-runtime"]
};
}
return viteConfig;
}
function src_default({ compat } = {}) {
function src_default({ include, exclude, compat, devtools } = {}) {
return {
name: "@astrojs/preact",
hooks: {
"astro:config:setup": ({ addRenderer, updateConfig, command }) => {
const development = command === "dev";
if (compat)
addRenderer(getCompatRenderer(development));
addRenderer(getRenderer(development));
"astro:config:setup": ({ addRenderer, updateConfig, command, injectScript }) => {
const preactPlugin = preact({
reactAliasesEnabled: compat ?? false,
include,
exclude,
babel: {
cwd: fileURLToPath(babelCwd)
}
});
const viteConfig = {
optimizeDeps: {
include: ["@astrojs/preact/client.js", "preact", "preact/jsx-runtime"],
exclude: ["@astrojs/preact/server.js"]
}
};
if (compat) {
viteConfig.optimizeDeps.include.push(
"preact/compat",
"preact/test-utils",
"preact/compat/jsx-runtime"
);
viteConfig.resolve = {
dedupe: ["preact/compat", "preact"]
};
viteConfig.ssr = {
noExternal: ["react", "react-dom", "react-dom/test-utils", "react/jsx-runtime"]
};
}
viteConfig.plugins = [preactPlugin];
addRenderer(getRenderer(command === "dev"));
updateConfig({
vite: getViteConfiguration(compat)
vite: viteConfig
});
if (command === "dev" && devtools) {
injectScript("page", 'import "preact/debug";');
}
}

@@ -92,3 +63,4 @@ }

export {
src_default as default
src_default as default,
getContainerRenderer
};

@@ -1,11 +0,13 @@

import type { AstroPreactAttrs, RendererContext } from './types';
declare function check(this: RendererContext, Component: any, props: Record<string, any>, children: any): boolean;
declare function renderToStaticMarkup(this: RendererContext, Component: any, props: Record<string, any>, { default: children, ...slotted }: Record<string, any>): {
import type { AstroComponentMetadata } from 'astro';
import type { AstroPreactAttrs, RendererContext } from './types.js';
declare function check(this: RendererContext, Component: any, props: Record<string, any>, children: any): Promise<boolean>;
declare function renderToStaticMarkup(this: RendererContext, Component: any, props: Record<string, any>, { default: children, ...slotted }: Record<string, any>, metadata: AstroComponentMetadata | undefined): Promise<{
attrs: AstroPreactAttrs;
html: string;
};
}>;
declare const _default: {
check: typeof check;
renderToStaticMarkup: typeof renderToStaticMarkup;
supportsAstroStaticSlot: boolean;
};
export default _default;
import { Component as BaseComponent, h } from "preact";
import render from "preact-render-to-string";
import { render } from "preact-render-to-string";
import prepass from "preact-ssr-prepass";
import { getContext } from "./context.js";

@@ -9,5 +10,5 @@ import { restoreSignalsOnProps, serializeSignals } from "./signals.js";

let consoleFilterRefs = 0;
function check(Component, props, children) {
if (typeof Component !== "function")
return false;
async function check(Component, props, children) {
if (typeof Component !== "function") return false;
if (Component.name === "QwikComponent") return false;
if (Component.prototype != null && typeof Component.prototype.render === "function") {

@@ -19,7 +20,7 @@ return BaseComponent.isPrototypeOf(Component);

try {
const { html } = renderToStaticMarkup.call(this, Component, props, children);
const { html } = await renderToStaticMarkup.call(this, Component, props, children, void 0);
if (typeof html !== "string") {
return false;
}
return !/\<undefined\>/.test(html);
return html == "" ? false : !/<undefined>/.test(html);
} catch (err) {

@@ -32,3 +33,6 @@ return false;

}
function renderToStaticMarkup(Component, props, { default: children, ...slotted }) {
function shouldHydrate(metadata) {
return metadata?.astroStaticSlot ? !!metadata.hydrate : true;
}
async function renderToStaticMarkup(Component, props, { default: children, ...slotted }, metadata) {
const ctx = getContext(this.result);

@@ -38,3 +42,7 @@ const slots = {};

const name = slotName(key);
slots[name] = h(StaticHtml, { value, name });
slots[name] = h(StaticHtml, {
hydrate: shouldHydrate(metadata),
value,
name
});
}

@@ -45,9 +53,13 @@ let propsMap = restoreSignalsOnProps(ctx, props);

serializeSignals(ctx, props, attrs, propsMap);
const html = render(
h(Component, newProps, children != null ? h(StaticHtml, { value: children }) : children)
const vNode = h(
Component,
newProps,
children != null ? h(StaticHtml, {
hydrate: shouldHydrate(metadata),
value: children
}) : children
);
return {
attrs,
html
};
await prepass(vNode);
const html = render(vNode);
return { attrs, html };
}

@@ -70,4 +82,3 @@ function useConsoleFilter() {

const isKnownReactHookError = msg.includes("Warning: Invalid hook call.") && msg.includes("https://reactjs.org/link/invalid-hook-call");
if (isKnownReactHookError)
return;
if (isKnownReactHookError) return;
}

@@ -78,3 +89,4 @@ originalConsoleError(msg, ...rest);

check,
renderToStaticMarkup
renderToStaticMarkup,
supportsAstroStaticSlot: true
};

@@ -81,0 +93,0 @@ export {

@@ -1,4 +0,4 @@

import type { Context } from './context';
import type { AstroPreactAttrs, PropNameToSignalMap } from './types';
import type { Context } from './context.js';
import type { AstroPreactAttrs, PropNameToSignalMap } from './types.js';
export declare function restoreSignalsOnProps(ctx: Context, props: Record<string, any>): PropNameToSignalMap;
export declare function serializeSignals(ctx: Context, props: Record<string, any>, attrs: AstroPreactAttrs, map: PropNameToSignalMap): void;

@@ -0,1 +1,7 @@

import { h } from 'preact';
type Props = {
value: string;
name?: string;
hydrate?: boolean;
};
/**

@@ -9,6 +15,3 @@ * Astro passes `children` as a string of HTML, so we need

declare const StaticHtml: {
({ value, name }: {
value: string;
name?: string | undefined;
}): import("preact").VNode<any> | null;
({ value, name, hydrate }: Props): import("preact").VNode<(import("preact").ClassAttributes<HTMLElement> & h.JSX.HTMLAttributes<EventTarget> & h.JSX.SVGAttributes<SVGElement>) | null> | null;
/**

@@ -15,0 +18,0 @@ * This tells Preact to opt-out of re-rendering this subtree,

import { h } from "preact";
const StaticHtml = ({ value, name }) => {
if (!value)
return null;
return h("astro-slot", { name, dangerouslySetInnerHTML: { __html: value } });
const StaticHtml = ({ value, name, hydrate = true }) => {
if (!value) return null;
const tagName = hydrate ? "astro-slot" : "astro-static-slot";
return h(tagName, { name, dangerouslySetInnerHTML: { __html: value } });
};

@@ -7,0 +7,0 @@ StaticHtml.shouldComponentUpdate = () => false;

import type { SSRResult } from 'astro';
export declare type RendererContext = {
export type RendererContext = {
result: SSRResult;
};
export declare type SignalLike = {
export type SignalLike = {
peek(): any;
};
export declare type PropNameToSignalMap = Map<string, SignalLike>;
export declare type AstroPreactAttrs = {
export type PropNameToSignalMap = Map<string, SignalLike>;
export type AstroPreactAttrs = {
['data-preact-signals']?: string;
};
{
"name": "@astrojs/preact",
"description": "Use Preact components within Astro",
"version": "0.0.0-cloudcannon-fix-20230306211609",
"version": "0.0.0-container-20240524151016",
"type": "module",

@@ -29,13 +29,18 @@ "types": "./dist/index.d.ts",

},
"files": [
"dist"
],
"dependencies": {
"@babel/core": ">=7.0.0-0 <8.0.0",
"@babel/plugin-transform-react-jsx": "^7.17.12",
"babel-plugin-module-resolver": "^5.0.0",
"preact-render-to-string": "^5.2.4",
"@preact/signals": "^1.1.0"
"@babel/plugin-transform-react-jsx": "^7.23.4",
"@babel/plugin-transform-react-jsx-development": "^7.22.5",
"@preact/preset-vite": "^2.8.2",
"@preact/signals": "^1.2.3",
"babel-plugin-transform-hook-names": "^1.0.2",
"preact-render-to-string": "~6.3.1",
"preact-ssr-prepass": "^1.2.1"
},
"devDependencies": {
"astro": "0.0.0-cloudcannon-fix-20230306211609",
"astro-scripts": "0.0.0-cloudcannon-fix-20230306211609",
"preact": "^10.7.3"
"preact": "^10.21.0",
"astro": "0.0.0-container-20240524151016",
"astro-scripts": "0.0.14"
},

@@ -46,4 +51,7 @@ "peerDependencies": {

"engines": {
"node": ">=16.12.0"
"node": "^18.17.1 || ^20.3.0 || >=21.0.0"
},
"publishConfig": {
"provenance": true
},
"scripts": {

@@ -50,0 +58,0 @@ "build": "astro-scripts build \"src/**/*.ts\" && tsc",

@@ -5,139 +5,35 @@ # @astrojs/preact ⚛️

- <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>
## Documentation
## Why Preact?
Read the [`@astrojs/preact` docs][docs]
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.
## Support
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).
- Get help in the [Astro Discord][discord]. Post questions in our `#support` forum, or visit our dedicated `#dev` channel to discuss current development and more!
**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.
- Check our [Astro Integration Documentation][astro-integration] for more on integrations.
## Installation
- Submit bug reports and feature requests as [GitHub issues][issues].
### Quick Install
## Contributing
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.
This package is maintained by Astro's Core team. You're welcome to submit an issue or PR! These links will help you get started:
```sh
# Using NPM
npx astro add preact
# Using Yarn
yarn astro add preact
# Using PNPM
pnpm astro add preact
```
- [Contributor Manual][contributing]
- [Code of Conduct][coc]
- [Community Guide][community]
If you run into any issues, [feel free to report them to us on GitHub](https://github.com/withastro/astro/issues) and try the manual installation steps below.
## License
### Manual Install
MIT
First, install the `@astrojs/preact` package using your package manager. If you're using npm or aren't sure, run this in the terminal:
Copyright (c) 2023–present [Astro][astro]
```sh
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
```
Then, apply this integration to your `astro.config.*` file using the `integrations` property:
__`astro.config.mjs`__
```js ins={2} "preact()"
import { defineConfig } from 'astro/config';
import preact from '@astrojs/preact';
export default defineConfig({
// ...
integrations: [preact()],
});
```
## 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,
- 💧 client-side hydration options, and
- 🤝 opportunities to mix and nest frameworks together
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.
### compat
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`.
__`astro.config.mjs`__
```js "compat: true"
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.
When importing React component libraries, in order to swap out the `react` and `react-dom` dependencies as `preact/compat`, you can use [`overrides`](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides) to do so.
```js
// package.json
{
"overrides": {
"react": "npm:@preact/compat@latest",
"react-dom": "npm:@preact/compat@latest"
}
}
```
Check out the [`pnpm` overrides](https://pnpm.io/package_json#pnpmoverrides) and [`yarn` resolutions](https://yarnpkg.com/configuration/manifest#resolutions) docs for their respective overrides features.
> **Note**
> Currently, the `compat` option only works for React libraries that export code as ESM. If an error happens during build-time, try adding the library to `vite.ssr.noExternal: ['the-react-library']` in your `astro.config.mjs` file.
## 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` 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]: https://astro.build/
[docs]: https://docs.astro.build/en/guides/integrations-guide/preact/
[contributing]: https://github.com/withastro/astro/blob/main/CONTRIBUTING.md
[coc]: https://github.com/withastro/.github/blob/main/CODE_OF_CONDUCT.md
[community]: https://github.com/withastro/.github/blob/main/COMMUNITY_GUIDE.md
[discord]: https://astro.build/chat/
[issues]: https://github.com/withastro/astro/issues
[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

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc