Skip to content

Commit

Permalink
Refactor MDX transformJSX handling
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Apr 5, 2024
1 parent 4d28994 commit 60e5b34
Show file tree
Hide file tree
Showing 7 changed files with 161 additions and 190 deletions.
2 changes: 1 addition & 1 deletion packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export async function createVite(
envVitePlugin({ settings }),
markdownVitePlugin({ settings, logger }),
htmlVitePlugin(),
mdxVitePlugin({ settings, logger }),
mdxVitePlugin(),
astroPostprocessVitePlugin(),
astroIntegrationsContainerPlugin({ settings, logger }),
astroScriptsPageSSRPlugin({ settings }),
Expand Down
14 changes: 2 additions & 12 deletions packages/astro/src/jsx/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import type { AstroRenderer } from '../@types/astro.js';
import { jsxTransformOptions } from './transform-options.js';

const renderer: AstroRenderer = {
name: 'astro:jsx',
serverEntrypoint: 'astro/jsx/server.js',
jsxImportSource: 'astro',
jsxTransformOptions: async () => {
// @ts-expect-error types not found
const plugin = await import('@babel/plugin-transform-react-jsx');
const jsx = plugin.default?.default ?? plugin.default;
const { default: astroJSX } = await import('./babel.js');
return {
plugins: [
astroJSX(),
jsx({}, { throwIfNamespace: false, runtime: 'automatic', importSource: 'astro' }),
],
};
},
jsxTransformOptions,
};

export default renderer;
14 changes: 14 additions & 0 deletions packages/astro/src/jsx/transform-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { JSXTransformConfig } from '../@types/astro.js';

export async function jsxTransformOptions(): Promise<JSXTransformConfig> {
// @ts-expect-error types not found
const plugin = await import('@babel/plugin-transform-react-jsx');
const jsx = plugin.default?.default ?? plugin.default;
const { default: astroJSX } = await import('./babel.js');
return {
plugins: [
astroJSX(),
jsx({}, { throwIfNamespace: false, runtime: 'automatic', importSource: 'astro' }),
],
};
}
4 changes: 2 additions & 2 deletions packages/astro/src/vite-plugin-mdx/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# vite-plugin-jsx
# vite-plugin-mdx

Modifies Vite’s built-in JSX behavior to allow for React, Preact, and Solid.js to coexist and all use `.jsx` and `.tsx` extensions.
Handles transforming MDX via the `astro:jsx` renderer.
31 changes: 4 additions & 27 deletions packages/astro/src/vite-plugin-mdx/index.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,19 @@
import { type Plugin, type ResolvedConfig, transformWithEsbuild } from 'vite';
import type { AstroRenderer, AstroSettings } from '../@types/astro.js';
import type { Logger } from '../core/logger/core.js';

import { type Plugin, transformWithEsbuild } from 'vite';
import { CONTENT_FLAG, PROPAGATED_ASSET_FLAG } from '../content/index.js';
import { astroEntryPrefix } from '../core/build/plugins/plugin-component-entry.js';
import { removeQueryString } from '../core/path.js';
import { transformJSX } from './transform-jsx.js';

interface AstroPluginJSXOptions {
settings: AstroSettings;
logger: Logger;
}

// Format inspired by https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts#L54
const SPECIAL_QUERY_REGEX = new RegExp(
`[?&](?:worker|sharedworker|raw|url|${CONTENT_FLAG}|${PROPAGATED_ASSET_FLAG})\\b`
);

/** Use Astro config to allow for alternate or multiple JSX renderers (by default Vite will assume React) */
export default function mdxVitePlugin({ settings }: AstroPluginJSXOptions): Plugin {
let viteConfig: ResolvedConfig;
// A reference to Astro's internal JSX renderer.
let astroJSXRenderer: AstroRenderer;

// TODO: Move this Vite plugin into `@astrojs/mdx` in Astro 5
export default function mdxVitePlugin(): Plugin {
return {
name: 'astro:jsx',
enforce: 'pre', // run transforms before other plugins
async configResolved(resolvedConfig) {
viteConfig = resolvedConfig;
astroJSXRenderer = settings.renderers.find((r) => r.jsxImportSource === 'astro')!;
},
async transform(code, id, opts) {
// Skip special queries and astro entries. We skip astro entries here as we know it doesn't contain
// JSX code, and also because we can't detect the import source to apply JSX transforms.
Expand All @@ -53,14 +37,7 @@ export default function mdxVitePlugin({ settings }: AstroPluginJSXOptions): Plug
},
},
});
return transformJSX({
code: jsxCode,
id,
renderer: astroJSXRenderer,
mode: viteConfig.mode,
ssr: Boolean(opts?.ssr),
root: settings.config.root,
});
return await transformJSX(jsxCode, id, opts?.ssr);
},
};
}
200 changes: 94 additions & 106 deletions packages/astro/src/vite-plugin-mdx/tag.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { PluginObj } from '@babel/core';
import * as t from '@babel/types';
import astroJsxRenderer from '../jsx/renderer.js';

const rendererName = astroJsxRenderer.name;

/**
* This plugin handles every file that runs through our JSX plugin.
Expand All @@ -9,115 +12,100 @@ import * as t from '@babel/types';
* This plugin crawls each export in the file and "tags" each export with a given `rendererName`.
* This allows us to automatically match a component to a renderer and skip the usual `check()` calls.
*/
export default async function tagExportsWithRenderer({
rendererName,
}: {
rendererName: string;
root: URL;
}): Promise<PluginObj> {
return {
visitor: {
Program: {
// Inject `import { __astro_tag_component__ } from 'astro/runtime/server/index.js'`
enter(path) {
path.node.body.splice(
0,
0,
t.importDeclaration(
[
t.importSpecifier(
t.identifier('__astro_tag_component__'),
t.identifier('__astro_tag_component__')
),
],
t.stringLiteral('astro/runtime/server/index.js')
)
);
},
// For each export we found, inject `__astro_tag_component__(exportName, rendererName)`
exit(path, state) {
const exportedIds = state.get('astro:tags');
if (exportedIds) {
for (const id of exportedIds) {
path.node.body.push(
t.expressionStatement(
t.callExpression(t.identifier('__astro_tag_component__'), [
t.identifier(id),
t.stringLiteral(rendererName),
])
)
);
}
}
},
export const tagExportsPlugin: PluginObj = {
visitor: {
Program: {
// Inject `import { __astro_tag_component__ } from 'astro/runtime/server/index.js'`
enter(path) {
path.node.body.splice(
0,
0,
t.importDeclaration(
[
t.importSpecifier(
t.identifier('__astro_tag_component__'),
t.identifier('__astro_tag_component__')
),
],
t.stringLiteral('astro/runtime/server/index.js')
)
);
},
ExportDeclaration: {
/**
* For default anonymous function export, we need to give them a unique name
* @param path
* @returns
*/
enter(path) {
const node = path.node;
if (!t.isExportDefaultDeclaration(node)) return;

if (
t.isArrowFunctionExpression(node.declaration) ||
t.isCallExpression(node.declaration)
) {
const varName = t.isArrowFunctionExpression(node.declaration)
? '_arrow_function'
: '_hoc_function';
const uidIdentifier = path.scope.generateUidIdentifier(varName);
path.insertBefore(
t.variableDeclaration('const', [
t.variableDeclarator(uidIdentifier, node.declaration),
])
// For each export we found, inject `__astro_tag_component__(exportName, rendererName)`
exit(path, state) {
const exportedIds = state.get('astro:tags');
if (exportedIds) {
for (const id of exportedIds) {
path.node.body.push(
t.expressionStatement(
t.callExpression(t.identifier('__astro_tag_component__'), [
t.identifier(id),
t.stringLiteral(rendererName),
])
)
);
node.declaration = uidIdentifier;
} else if (t.isFunctionDeclaration(node.declaration) && !node.declaration.id?.name) {
const uidIdentifier = path.scope.generateUidIdentifier('_function');
node.declaration.id = uidIdentifier;
}
},
exit(path, state) {
const node = path.node;
if (node.exportKind === 'type') return;
if (t.isExportAllDeclaration(node)) return;
const addTag = (id: string) => {
const tags = state.get('astro:tags') ?? [];
state.set('astro:tags', [...tags, id]);
};
if (t.isExportNamedDeclaration(node) || t.isExportDefaultDeclaration(node)) {
if (t.isIdentifier(node.declaration)) {
addTag(node.declaration.name);
} else if (t.isFunctionDeclaration(node.declaration) && node.declaration.id?.name) {
addTag(node.declaration.id.name);
} else if (t.isVariableDeclaration(node.declaration)) {
node.declaration.declarations?.forEach((declaration) => {
if (
t.isArrowFunctionExpression(declaration.init) &&
t.isIdentifier(declaration.id)
) {
addTag(declaration.id.name);
}
});
} else if (t.isObjectExpression(node.declaration)) {
node.declaration.properties?.forEach((property) => {
if (t.isProperty(property) && t.isIdentifier(property.key)) {
addTag(property.key.name);
}
});
} else if (t.isExportNamedDeclaration(node) && !node.source) {
node.specifiers.forEach((specifier) => {
if (t.isExportSpecifier(specifier) && t.isIdentifier(specifier.exported)) {
addTag(specifier.local.name);
}
});
}
}
},
},
ExportDeclaration: {
/**
* For default anonymous function export, we need to give them a unique name
* @param path
* @returns
*/
enter(path) {
const node = path.node;
if (!t.isExportDefaultDeclaration(node)) return;

if (t.isArrowFunctionExpression(node.declaration) || t.isCallExpression(node.declaration)) {
const varName = t.isArrowFunctionExpression(node.declaration)
? '_arrow_function'
: '_hoc_function';
const uidIdentifier = path.scope.generateUidIdentifier(varName);
path.insertBefore(
t.variableDeclaration('const', [t.variableDeclarator(uidIdentifier, node.declaration)])
);
node.declaration = uidIdentifier;
} else if (t.isFunctionDeclaration(node.declaration) && !node.declaration.id?.name) {
const uidIdentifier = path.scope.generateUidIdentifier('_function');
node.declaration.id = uidIdentifier;
}
},
exit(path, state) {
const node = path.node;
if (node.exportKind === 'type') return;
if (t.isExportAllDeclaration(node)) return;
const addTag = (id: string) => {
const tags = state.get('astro:tags') ?? [];
state.set('astro:tags', [...tags, id]);
};
if (t.isExportNamedDeclaration(node) || t.isExportDefaultDeclaration(node)) {
if (t.isIdentifier(node.declaration)) {
addTag(node.declaration.name);
} else if (t.isFunctionDeclaration(node.declaration) && node.declaration.id?.name) {
addTag(node.declaration.id.name);
} else if (t.isVariableDeclaration(node.declaration)) {
node.declaration.declarations?.forEach((declaration) => {
if (t.isArrowFunctionExpression(declaration.init) && t.isIdentifier(declaration.id)) {
addTag(declaration.id.name);
}
});
} else if (t.isObjectExpression(node.declaration)) {
node.declaration.properties?.forEach((property) => {
if (t.isProperty(property) && t.isIdentifier(property.key)) {
addTag(property.key.name);
}
});
} else if (t.isExportNamedDeclaration(node) && !node.source) {
node.specifiers.forEach((specifier) => {
if (t.isExportSpecifier(specifier) && t.isIdentifier(specifier.exported)) {
addTag(specifier.local.name);
}
});
}
},
}
},
},
};
}
},
};
Loading

0 comments on commit 60e5b34

Please sign in to comment.