Warn hydration directive for Astro components in JSX (#4330)

* Warn hydration directive for Astro components in JSX

* Add changeset

* Better comment
This commit is contained in:
Bjorn Lu 2022-08-23 22:38:31 +08:00 committed by GitHub
parent dc42f2c00f
commit baa2ddd010
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Warn hydration directive for Astro components in JSX

View file

@ -1,6 +1,7 @@
import type { PluginObj } from '@babel/core'; import type { PluginObj } from '@babel/core';
import * as t from '@babel/types'; import * as t from '@babel/types';
import { pathToFileURL } from 'node:url'; import { pathToFileURL } from 'node:url';
import { HydrationDirectiveProps } from '../runtime/server/hydration.js';
import type { PluginMetadata } from '../vite-plugin-astro/types'; import type { PluginMetadata } from '../vite-plugin-astro/types';
const ClientOnlyPlaceholder = 'astro-client-only'; const ClientOnlyPlaceholder = 'astro-client-only';
@ -280,6 +281,22 @@ export default function astroJSX(): PluginObj {
const meta = path.getData('import'); const meta = path.getData('import');
if (meta) { if (meta) {
// If JSX is importing an Astro component, e.g. using MDX for templating,
// check Astro node's props and make sure they are valid for an Astro component
if (meta.path.endsWith('.astro')) {
const displayName = getTagName(parentNode);
for (const attr of parentNode.openingElement.attributes) {
if (t.isJSXAttribute(attr)) {
const name = jsxAttributeToString(attr);
if (HydrationDirectiveProps.has(name)) {
// eslint-disable-next-line
console.warn(
`You are attempting to render <${displayName} ${name} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`
);
}
}
}
}
let resolvedPath: string; let resolvedPath: string;
if (meta.path.startsWith('.')) { if (meta.path.startsWith('.')) {
const fileURL = pathToFileURL(state.filename!); const fileURL = pathToFileURL(state.filename!);