Move MDX plugin re-ordering hack to MDX integration (#7872)

This commit is contained in:
Bjorn Lu 2023-07-31 21:51:37 +08:00 committed by Emanuele Stoppa
parent dd3054d150
commit dfc2d93e3c
6 changed files with 33 additions and 25 deletions

View file

@ -0,0 +1,5 @@
---
'@astrojs/mdx': patch
---
Re-orders the MDX plugin to run before Astro's JSX plugin

View file

@ -0,0 +1,5 @@
---
'astro': major
---
Remove MDX plugin re-ordering hack

View file

@ -0,0 +1,5 @@
---
'@astrojs/mdx': minor
---
Add `astro` as peer dependency

View file

@ -234,37 +234,12 @@ export async function createVite(
result = vite.mergeConfig(result, settings.config.vite || {});
}
result = vite.mergeConfig(result, commandConfig);
if (result.plugins) {
sortPlugins(result.plugins);
}
result.customLogger = vite.createLogger(result.logLevel ?? 'warn');
return result;
}
function isVitePlugin(plugin: vite.PluginOption): plugin is vite.Plugin {
return Boolean(plugin?.hasOwnProperty('name'));
}
function findPluginIndexByName(pluginOptions: vite.PluginOption[], name: string): number {
return pluginOptions.findIndex(function (pluginOption) {
// Use isVitePlugin to ignore nulls, booleans, promises, and arrays
// CAUTION: could be a problem if a plugin we're searching for becomes async!
return isVitePlugin(pluginOption) && pluginOption.name === name;
});
}
function sortPlugins(pluginOptions: vite.PluginOption[]) {
// HACK: move mdxPlugin to top because it needs to run before internal JSX plugin
const mdxPluginIndex = findPluginIndexByName(pluginOptions, '@mdx-js/rollup');
if (mdxPluginIndex === -1) return;
const jsxPluginIndex = findPluginIndexByName(pluginOptions, 'astro:jsx');
const mdxPlugin = pluginOptions[mdxPluginIndex];
pluginOptions.splice(mdxPluginIndex, 1);
pluginOptions.splice(jsxPluginIndex, 0, mdxPlugin);
}
const COMMON_DEPENDENCIES_NOT_ASTRO = [
'autoprefixer',
'react',

View file

@ -53,6 +53,9 @@
"unist-util-visit": "^4.1.2",
"vfile": "^5.3.7"
},
"peerDependencies": {
"astro": "workspace:^2.9.6"
},
"devDependencies": {
"@types/chai": "^4.3.5",
"@types/estree": "^1.0.1",

View file

@ -95,6 +95,21 @@ export default function mdx(partialMdxOptions: Partial<MdxOptions> = {}): AstroI
enforce: 'pre',
configResolved(resolved) {
importMetaEnv = { ...importMetaEnv, ...resolved.env };
// HACK: move ourselves before Astro's JSX plugin to transform things in the right order
const jsxPluginIndex = resolved.plugins.findIndex((p) => p.name === 'astro:jsx');
if (jsxPluginIndex !== -1) {
const myPluginIndex = resolved.plugins.findIndex(
(p) => p.name === '@mdx-js/rollup'
);
if (myPluginIndex !== -1) {
const myPlugin = resolved.plugins[myPluginIndex];
// @ts-ignore-error ignore readonly annotation
resolved.plugins.splice(myPluginIndex, 1);
// @ts-ignore-error ignore readonly annotation
resolved.plugins.splice(jsxPluginIndex, 0, myPlugin);
}
}
},
// Override transform to alter code before MDX compilation
// ex. inject layouts