diff --git a/.changeset/large-glasses-jam.md b/.changeset/large-glasses-jam.md new file mode 100644 index 000000000000..885471d82fba --- /dev/null +++ b/.changeset/large-glasses-jam.md @@ -0,0 +1,5 @@ +--- +"@astrojs/mdx": patch +--- + +Allows Vite plugins to transform `.mdx` files before the MDX plugin transforms it diff --git a/packages/integrations/mdx/src/index.ts b/packages/integrations/mdx/src/index.ts index fc1d92da48ca..cc831704ff9e 100644 --- a/packages/integrations/mdx/src/index.ts +++ b/packages/integrations/mdx/src/index.ts @@ -70,7 +70,7 @@ export default function mdx(partialMdxOptions: Partial = {}): AstroI updateConfig({ vite: { - plugins: [vitePluginMdx(config, mdxOptions), vitePluginMdxPostprocess(config)], + plugins: [vitePluginMdx(mdxOptions), vitePluginMdxPostprocess(config)], }, }); }, diff --git a/packages/integrations/mdx/src/vite-plugin-mdx.ts b/packages/integrations/mdx/src/vite-plugin-mdx.ts index 6f2ec2cc487a..9e220ca2f57b 100644 --- a/packages/integrations/mdx/src/vite-plugin-mdx.ts +++ b/packages/integrations/mdx/src/vite-plugin-mdx.ts @@ -1,13 +1,12 @@ -import fs from 'node:fs/promises'; import { setVfileFrontmatter } from '@astrojs/markdown-remark'; -import type { AstroConfig, SSRError } from 'astro'; +import type { SSRError } from 'astro'; import { VFile } from 'vfile'; import type { Plugin } from 'vite'; import type { MdxOptions } from './index.js'; import { createMdxProcessor } from './plugins.js'; -import { getFileInfo, parseFrontmatter } from './utils.js'; +import { parseFrontmatter } from './utils.js'; -export function vitePluginMdx(astroConfig: AstroConfig, mdxOptions: MdxOptions): Plugin { +export function vitePluginMdx(mdxOptions: MdxOptions): Plugin { let processor: ReturnType | undefined; return { @@ -43,13 +42,9 @@ export function vitePluginMdx(astroConfig: AstroConfig, mdxOptions: MdxOptions): }, // Override transform to alter code before MDX compilation // ex. inject layouts - async transform(_, id) { + async transform(code, id) { if (!id.endsWith('.mdx')) return; - // Read code from file manually to prevent Vite from parsing `import.meta.env` expressions - const { fileId } = getFileInfo(id, astroConfig); - const code = await fs.readFile(fileId, 'utf-8'); - const { data: frontmatter, content: pageContent } = parseFrontmatter(code, id); const vfile = new VFile({ value: pageContent, path: id }); @@ -76,7 +71,7 @@ export function vitePluginMdx(astroConfig: AstroConfig, mdxOptions: MdxOptions): // For some reason MDX puts the error location in the error's name, not very useful for us. err.name = 'MDXError'; - err.loc = { file: fileId, line: e.line, column: e.column }; + err.loc = { file: id, line: e.line, column: e.column }; // For another some reason, MDX doesn't include a stack trace. Weird Error.captureStackTrace(err);