Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@astrojs/react

Package Overview
Dependencies
Maintainers
3
Versions
103
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@astrojs/react - npm Package Compare versions

Comparing version 0.0.0-schema-image-20230401013700 to 0.0.0-self-closing-children-20231120164333

context.js

13

client-v17.js
import { createElement } from 'react';
import { render, hydrate } from 'react-dom';
import { render, hydrate, unmountComponentAtNode } from 'react-dom';
import StaticHtml from './static-html.js';

@@ -15,6 +15,9 @@

);
if (client === 'only') {
return render(componentEl, element);
}
return hydrate(componentEl, element);
const isHydrate = client !== 'only';
const bootstrap = isHydrate ? hydrate : render;
bootstrap(componentEl, element);
element.addEventListener('astro:unmount', () => unmountComponentAtNode(element), {
once: true,
});
};

@@ -13,12 +13,55 @@ import { createElement, startTransition } from 'react';

function createReactElementFromDOMElement(element) {
let attrs = {};
for (const attr of element.attributes) {
attrs[attr.name] = attr.value;
}
return createElement(
element.localName,
attrs,
Array.from(element.childNodes)
.map((c) => {
if (c.nodeType === Node.TEXT_NODE) {
return c.data;
} else if (c.nodeType === Node.ELEMENT_NODE) {
return createReactElementFromDOMElement(c);
} else {
return undefined;
}
})
.filter((a) => !!a)
);
}
function getChildren(childString, experimentalReactChildren) {
if (experimentalReactChildren && childString) {
let children = [];
let template = document.createElement('template');
template.innerHTML = childString;
for (let child of template.content.children) {
children.push(createReactElementFromDOMElement(child));
}
return children;
} else if (childString) {
return createElement(StaticHtml, { value: childString });
} else {
return undefined;
}
}
export default (element) =>
(Component, props, { default: children, ...slotted }, { client }) => {
if (!element.hasAttribute('ssr')) return;
const renderOptions = {
identifierPrefix: element.getAttribute('prefix'),
};
for (const [key, value] of Object.entries(slotted)) {
props[key] = createElement(StaticHtml, { value, name: key });
}
const componentEl = createElement(
Component,
props,
children != null ? createElement(StaticHtml, { value: children }) : children
getChildren(children, element.hasAttribute('data-react-children'))
);

@@ -32,8 +75,12 @@ const rootKey = isAlreadyHydrated(element);

return startTransition(() => {
createRoot(element).render(componentEl);
const root = createRoot(element);
root.render(componentEl);
element.addEventListener('astro:unmount', () => root.unmount(), { once: true });
});
}
return startTransition(() => {
hydrateRoot(element, componentEl);
startTransition(() => {
const root = hydrateRoot(element, componentEl, renderOptions);
root.render(componentEl);
element.addEventListener('astro:unmount', () => root.unmount(), { once: true });
});
};

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

import { type Options as ViteReactPluginOptions } from '@vitejs/plugin-react';
import type { AstroIntegration } from 'astro';
export default function (): AstroIntegration;
export type ReactIntegrationOptions = Pick<ViteReactPluginOptions, 'include' | 'exclude'> & {
experimentalReactChildren?: boolean;
};
export default function ({ include, exclude, experimentalReactChildren, }?: ReactIntegrationOptions): AstroIntegration;

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

import react, {} from "@vitejs/plugin-react";
import { version as ReactVersion } from "react-dom";
const FAST_REFRESH_PREAMBLE = react.preambleCode;
function getRenderer() {

@@ -6,27 +8,31 @@ return {

clientEntrypoint: ReactVersion.startsWith("18.") ? "@astrojs/react/client.js" : "@astrojs/react/client-v17.js",
serverEntrypoint: ReactVersion.startsWith("18.") ? "@astrojs/react/server.js" : "@astrojs/react/server-v17.js",
jsxImportSource: "react",
jsxTransformOptions: async () => {
var _a;
const babelPluginTransformReactJsxModule = await import("@babel/plugin-transform-react-jsx");
const jsx = ((_a = babelPluginTransformReactJsxModule == null ? void 0 : babelPluginTransformReactJsxModule.default) == null ? void 0 : _a.default) ?? (babelPluginTransformReactJsxModule == null ? void 0 : babelPluginTransformReactJsxModule.default);
return {
plugins: [
jsx(
{},
{
runtime: "automatic",
// This option tells the JSX transform how to construct the "*/jsx-runtime" import.
// In React v17, we had to shim this due to an export map issue in React.
// In React v18, this issue was fixed and we can import "react/jsx-runtime" directly.
// See `./jsx-runtime.js` for more details.
importSource: ReactVersion.startsWith("18.") ? "react" : "@astrojs/react"
}
)
]
};
serverEntrypoint: ReactVersion.startsWith("18.") ? "@astrojs/react/server.js" : "@astrojs/react/server-v17.js"
};
}
function optionsPlugin(experimentalReactChildren) {
const virtualModule = "astro:react:opts";
const virtualModuleId = "\0" + virtualModule;
return {
name: "@astrojs/react:opts",
resolveId(id) {
if (id === virtualModule) {
return virtualModuleId;
}
},
load(id) {
if (id === virtualModuleId) {
return {
code: `export default {
experimentalReactChildren: ${JSON.stringify(experimentalReactChildren)}
}`
};
}
}
};
}
function getViteConfiguration() {
function getViteConfiguration({
include,
exclude,
experimentalReactChildren
} = {}) {
return {

@@ -45,4 +51,5 @@ optimizeDeps: {

},
plugins: [react({ include, exclude }), optionsPlugin(!!experimentalReactChildren)],
resolve: {
dedupe: ["react", "react-dom"]
dedupe: ["react", "react-dom", "react-dom/server"]
},

@@ -56,2 +63,3 @@ ssr: {

"@babel/runtime",
"redoc",
"use-immer"

@@ -62,9 +70,19 @@ ]

}
function src_default() {
function src_default({
include,
exclude,
experimentalReactChildren
} = {}) {
return {
name: "@astrojs/react",
hooks: {
"astro:config:setup": ({ addRenderer, updateConfig }) => {
"astro:config:setup": ({ command, addRenderer, updateConfig, injectScript }) => {
addRenderer(getRenderer());
updateConfig({ vite: getViteConfiguration() });
updateConfig({
vite: getViteConfiguration({ include, exclude, experimentalReactChildren })
});
if (command === "dev") {
const preamble = FAST_REFRESH_PREAMBLE.replace(`__BASE__`, "/");
injectScript("before-hydration", preamble);
}
}

@@ -71,0 +89,0 @@ }

{
"name": "@astrojs/react",
"description": "Use React components within Astro",
"version": "0.0.0-schema-image-20230401013700",
"version": "0.0.0-self-closing-children-20231120164333",
"type": "module",

@@ -31,28 +31,47 @@ "types": "./dist/index.d.ts",

},
"files": [
"dist",
"client.js",
"client-v17.js",
"context.js",
"jsx-runtime.js",
"server.js",
"server-v17.js",
"static-html.js",
"vnode-children.js"
],
"dependencies": {
"@babel/core": ">=7.0.0-0 <8.0.0",
"@babel/plugin-transform-react-jsx": "^7.17.12"
"@vitejs/plugin-react": "^4.0.4",
"ultrahtml": "^1.3.0"
},
"devDependencies": {
"@types/react": "^17.0.45",
"@types/react-dom": "^17.0.17",
"astro": "0.0.0-schema-image-20230401013700",
"astro-scripts": "0.0.14",
"@types/react": "^18.2.21",
"@types/react-dom": "^18.2.7",
"chai": "^4.3.7",
"cheerio": "1.0.0-rc.12",
"react": "^18.1.0",
"react-dom": "^18.1.0"
"react-dom": "^18.1.0",
"vite": "^4.4.9",
"mocha": "^10.2.0",
"astro": "0.0.0-self-closing-children-20231120164333",
"astro-scripts": "0.0.14"
},
"peerDependencies": {
"@types/react": "^17.0.50 || ^18.0.21",
"@types/react-dom": "^17.0.17 || ^18.0.6",
"react": "^17.0.2 || ^18.0.0",
"react-dom": "^17.0.2 || ^18.0.0",
"@types/react": "^17.0.50 || ^18.0.21",
"@types/react-dom": "^17.0.17 || ^18.0.6"
"react-dom": "^17.0.2 || ^18.0.0"
},
"engines": {
"node": ">=16.12.0"
"node": ">=18.14.1"
},
"publishConfig": {
"provenance": true
},
"scripts": {
"build": "astro-scripts build \"src/**/*.ts\" && tsc",
"build:ci": "astro-scripts build \"src/**/*.ts\"",
"dev": "astro-scripts dev \"src/**/*.ts\""
"dev": "astro-scripts dev \"src/**/*.ts\"",
"test": "mocha --exit --timeout 20000"
}
}

@@ -12,2 +12,3 @@ # @astrojs/react ⚛️

Astro includes a CLI tool for adding first party integrations: `astro add`. This command will:
1. (Optionally) Install all necessary dependencies and peer dependencies

@@ -45,12 +46,12 @@ 2. (Also optionally) Update your `astro.config.*` file to apply this integration

__`astro.config.mjs`__
```diff lang="js" "react()"
// astro.config.mjs
import { defineConfig } from 'astro/config';
+ import react from '@astrojs/react';
```js ins={2} "react()"
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
// ...
integrations: [react()],
});
export default defineConfig({
// ...
integrations: [react()],
// ^^^^^^^
});
```

@@ -61,2 +62,3 @@

To use your first React component in Astro, head to our [UI framework documentation][astro-ui-frameworks]. You'll explore:
- 📦 how framework components are loaded,

@@ -66,2 +68,76 @@ - 💧 client-side hydration options, and

## Options
### Combining multiple JSX frameworks
When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed.
Use the `include` (required) and `exclude` (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to `include` for each framework you are using. Wildcards may be used to include multiple file paths.
We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required:
```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import preact from '@astrojs/preact';
import react from '@astrojs/react';
import svelte from '@astrojs/svelte';
import vue from '@astrojs/vue';
import solid from '@astrojs/solid-js';
export default defineConfig({
// Enable many frameworks to support all different kinds of components.
// No `include` is needed if you are only using a single JSX framework!
integrations: [
preact({
include: ['**/preact/*'],
}),
react({
include: ['**/react/*'],
}),
solid({
include: ['**/solid/*'],
}),
],
});
```
### Children parsing
Children passed into a React component from an Astro component are parsed as plain strings, not React nodes.
For example, the `<ReactComponent />` below will only receive a single child element:
```astro
---
import ReactComponent from './ReactComponent';
---
<ReactComponent>
<div>one</div>
<div>two</div>
</ReactComponent>
```
If you are using a library that _expects_ more than one child element to be passed, for example so that it can slot certain elements in different places, you might find this to be a blocker.
You can set the experimental flag `experimentalReactChildren` to tell Astro to always pass children to React as React vnodes. There is some runtime cost to this, but it can help with compatibility.
You can enable this option in the configuration for the React integration:
```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
// ...
integrations: [
react({
experimentalReactChildren: true,
}),
],
});
```
## Troubleshooting

@@ -68,0 +144,0 @@

@@ -20,4 +20,3 @@ import React from 'react';

if (typeof Component === 'object') {
const $$typeof = Component['$$typeof'];
return $$typeof && $$typeof.toString().slice('Symbol('.length).startsWith('react');
return Component['$$typeof']?.toString().slice('Symbol('.length).startsWith('react');
}

@@ -69,7 +68,11 @@ if (typeof Component !== 'function') return false;

if (newChildren != null) {
newProps.children = React.createElement(StaticHtml, { value: newChildren });
newProps.children = React.createElement(StaticHtml, {
// Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
hydrate: metadata.astroStaticSlot ? !!metadata.hydrate : true,
value: newChildren,
});
}
const vnode = React.createElement(Component, newProps);
let html;
if (metadata && metadata.hydrate) {
if (metadata?.hydrate) {
html = ReactDOM.renderToString(vnode);

@@ -85,2 +88,3 @@ } else {

renderToStaticMarkup,
supportsAstroStaticSlot: true,
};
import React from 'react';
import ReactDOM from 'react-dom/server';
import StaticHtml from './static-html.js';
import { incrementId } from './context.js';
import opts from 'astro:react:opts';

@@ -20,4 +22,3 @@ const slotName = (str) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase());

if (typeof Component === 'object') {
const $$typeof = Component['$$typeof'];
return $$typeof && $$typeof.toString().slice('Symbol('.length).startsWith('react');
return Component['$$typeof'].toString().slice('Symbol('.length).startsWith('react');
}

@@ -56,3 +57,3 @@ if (typeof Component !== 'function') return false;

async function getNodeWritable() {
let nodeStreamBuiltinModuleName = 'stream';
let nodeStreamBuiltinModuleName = 'node:stream';
let { Writable } = await import(/* @vite-ignore */ nodeStreamBuiltinModuleName);

@@ -62,3 +63,14 @@ return Writable;

function needsHydration(metadata) {
// Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
return metadata.astroStaticSlot ? !!metadata.hydrate : true;
}
async function renderToStaticMarkup(Component, props, { default: children, ...slotted }, metadata) {
let prefix;
if (this && this.result) {
prefix = incrementId(this.result);
}
const attrs = { prefix };
delete props['class'];

@@ -68,3 +80,7 @@ const slots = {};

const name = slotName(key);
slots[name] = React.createElement(StaticHtml, { value, name });
slots[name] = React.createElement(StaticHtml, {
hydrate: needsHydration(metadata),
value,
name,
});
}

@@ -77,24 +93,34 @@ // Note: create newProps to avoid mutating `props` before they are serialized

const newChildren = children ?? props.children;
if (newChildren != null) {
newProps.children = React.createElement(StaticHtml, { value: newChildren });
if (children && opts.experimentalReactChildren) {
attrs['data-react-children'] = true;
const convert = await import('./vnode-children.js').then((mod) => mod.default);
newProps.children = convert(children);
} else if (newChildren != null) {
newProps.children = React.createElement(StaticHtml, {
hydrate: needsHydration(metadata),
value: newChildren,
});
}
const vnode = React.createElement(Component, newProps);
const renderOptions = {
identifierPrefix: prefix,
};
let html;
if (metadata && metadata.hydrate) {
if (metadata?.hydrate) {
if ('renderToReadableStream' in ReactDOM) {
html = await renderToReadableStreamAsync(vnode);
html = await renderToReadableStreamAsync(vnode, renderOptions);
} else {
html = await renderToPipeableStreamAsync(vnode);
html = await renderToPipeableStreamAsync(vnode, renderOptions);
}
} else {
if ('renderToReadableStream' in ReactDOM) {
html = await renderToReadableStreamAsync(vnode);
html = await renderToReadableStreamAsync(vnode, renderOptions);
} else {
html = await renderToStaticNodeStreamAsync(vnode);
html = await renderToStaticNodeStreamAsync(vnode, renderOptions);
}
}
return { html };
return { html, attrs };
}
async function renderToPipeableStreamAsync(vnode) {
async function renderToPipeableStreamAsync(vnode, options) {
const Writable = await getNodeWritable();

@@ -105,2 +131,3 @@ let html = '';

let stream = ReactDOM.renderToPipeableStream(vnode, {
...options,
onError(err) {

@@ -127,7 +154,7 @@ error = err;

async function renderToStaticNodeStreamAsync(vnode) {
async function renderToStaticNodeStreamAsync(vnode, options) {
const Writable = await getNodeWritable();
let html = '';
return new Promise((resolve, reject) => {
let stream = ReactDOM.renderToStaticNodeStream(vnode);
let stream = ReactDOM.renderToStaticNodeStream(vnode, options);
stream.on('error', (err) => {

@@ -174,4 +201,4 @@ reject(err);

async function renderToReadableStreamAsync(vnode) {
return await readResult(await ReactDOM.renderToReadableStream(vnode));
async function renderToReadableStreamAsync(vnode, options) {
return await readResult(await ReactDOM.renderToReadableStream(vnode, options));
}

@@ -182,2 +209,3 @@

renderToStaticMarkup,
supportsAstroStaticSlot: true,
};

@@ -10,5 +10,6 @@ import { createElement as h } from 'react';

*/
const StaticHtml = ({ value, name }) => {
const StaticHtml = ({ value, name, hydrate = true }) => {
if (!value) return null;
return h('astro-slot', {
const tagName = hydrate ? 'astro-slot' : 'astro-static-slot';
return h(tagName, {
name,

@@ -15,0 +16,0 @@ suppressHydrationWarning: true,

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