Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow automatic JSX runtime alongside MDX #4160

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/slow-frogs-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'astro': patch
'@astrojs/mdx': patch
---

Allow automatic JSX runtime with MDX
8 changes: 8 additions & 0 deletions packages/astro/src/jsx/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,21 @@ export default function astroJSX(): PluginObj {
visitor: {
Program: {
enter(path, state) {
const { file } = state;
if (!(state.file.metadata as PluginMetadata).astro) {
(state.file.metadata as PluginMetadata).astro = {
clientOnlyComponents: [],
hydratedComponents: [],
scripts: [],
};
}
if(!file.ast.comments) {
file.ast.comments = [];
}
file.ast.comments?.push({
type: 'CommentBlock',
value: '* @jsxImportSource astro '
});
path.node.body.splice(
0,
0,
Expand Down
3 changes: 1 addition & 2 deletions packages/astro/src/jsx/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const renderer = {
name: 'astro:jsx',
serverEntrypoint: 'astro/jsx/server.js',
jsxImportSource: 'astro',
jsxTransformOptions: async () => {
const {
default: { default: jsx },
Expand All @@ -11,7 +10,7 @@ const renderer = {
return {
plugins: [
astroJSX(),
jsx({}, { throwIfNamespace: false, runtime: 'automatic', importSource: 'astro' }),
jsx({}, { throwIfNamespace: false, runtime: 'automatic' }),
],
};
},
Expand Down
18 changes: 15 additions & 3 deletions packages/astro/src/vite-plugin-jsx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { parseNpmName } from '../core/util.js';
import tagExportsPlugin from './tag.js';

const JSX_RENDERER_CACHE = new WeakMap<AstroConfig, Map<string, AstroRenderer>>();
const JSX_RENDERER_WITH_AUTO_CACHE = new WeakMap<AstroConfig, AstroRenderer[]>();
const JSX_EXTENSIONS = new Set(['.jsx', '.tsx', '.mdx']);
const IMPORT_STATEMENTS: Record<string, string> = {
react: "import React from 'react'",
Expand All @@ -33,7 +34,7 @@ function getEsbuildLoader(fileExt: string): string {
}

function collectJSXRenderers(renderers: AstroRenderer[]): Map<string, AstroRenderer> {
const renderersWithJSXSupport = renderers.filter((r) => r.jsxImportSource);
const renderersWithJSXSupport = renderers.filter((r) => r.jsxImportSource || r.jsxTransformOptions);
return new Map(
renderersWithJSXSupport.map((r) => [r.jsxImportSource, r] as [string, AstroRenderer])
);
Expand Down Expand Up @@ -69,6 +70,7 @@ async function transformJSX({
babelrc: false,
inputSourceMap: options.inputSourceMap,
});

// TODO: Be more strict about bad return values here.
// Should we throw an error instead? Should we never return `{code: ""}`?
if (!result) return null;
Expand Down Expand Up @@ -118,6 +120,7 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin

const { mode } = viteConfig;
let jsxRenderers = JSX_RENDERER_CACHE.get(config);
let jsxAutoRenderers = JSX_RENDERER_WITH_AUTO_CACHE.get(config);

// load renderers (on first run only)
if (!jsxRenderers) {
Expand All @@ -136,10 +139,19 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin
}
JSX_RENDERER_CACHE.set(config, jsxRenderers);
}
if(!jsxAutoRenderers) {
jsxAutoRenderers = [];
for(const [,renderer] of jsxRenderers) {
if(renderer.jsxImportSource) {
jsxAutoRenderers.push(renderer);
}
}
}

// Attempt: Single JSX renderer
// If we only have one renderer, we can skip a bunch of work!
if (jsxRenderers.size === 1) {
if (jsxAutoRenderers.length === 1 || jsxRenderers.size === 1) {
const renderer = jsxAutoRenderers.length ? jsxAutoRenderers[0] : Array.from(jsxRenderers.values())[0];
// downlevel any non-standard syntax, but preserve JSX
const { code: jsxCode } = await esbuild.transform(code, {
loader: getEsbuildLoader(path.extname(id)) as esbuild.Loader,
Expand All @@ -150,7 +162,7 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin
return transformJSX({
code: jsxCode,
id,
renderer: [...jsxRenderers.values()][0],
renderer,
mode,
ssr,
});
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/vite-plugin-jsx/tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default function tagExportsWithRenderer({
// Inject `import { __astro_tag_component__ } from 'astro/server/index.js'`
enter(path) {
path.node.body.splice(
0,
1,
0,
t.importDeclaration(
[
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import mdx from '@astrojs/mdx';
import react from '@astrojs/react';

export default {
integrations: [react(), mdx()]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "@test/mdx-plus-react",
"dependencies": {
"astro": "workspace:*",
"@astrojs/mdx": "workspace:*",
"@astrojs/react": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const Component = () => {
return <p>Hello world</p>;
};

export default Component;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
import Component from "../components/Component.jsx";
---
<html>
<head>
<title>Testing</title>
</head>
<body>
<Component />
</body>
</html>
25 changes: 25 additions & 0 deletions packages/integrations/mdx/test/mdx-plus-react.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import mdx from '@astrojs/mdx';

import { expect } from 'chai';
import { parseHTML } from 'linkedom';
import { loadFixture } from '../../../astro/test/test-utils.js';

describe('MDX and React', () => {
let fixture;

before(async () => {
fixture = await loadFixture({
root: new URL('./fixtures/mdx-plus-react/', import.meta.url),
});
await fixture.build();
});

it('can be used in the same project', async () => {
const html = await fixture.readFile('/index.html');
const { document } = parseHTML(html);

const p = document.querySelector('p');

expect(p.textContent).to.equal('Hello world');
});
});
7 changes: 3 additions & 4 deletions packages/integrations/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ function getRenderer() {
: '@astrojs/react/server-v17.js',
jsxImportSource: 'react',
jsxTransformOptions: async () => {
const {
default: { default: jsx },
// @ts-expect-error types not found
} = await import('@babel/plugin-transform-react-jsx');
// @ts-expect-error types not found
const babelPluginTransformReactJsxModule = await import('@babel/plugin-transform-react-jsx');
const jsx = babelPluginTransformReactJsxModule?.default?.default ?? babelPluginTransformReactJsxModule?.default;
return {
plugins: [
jsx(
Expand Down
10 changes: 10 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.