diff options
Diffstat (limited to 'packages/integrations/mdx/src')
-rw-r--r-- | packages/integrations/mdx/src/index.ts | 23 | ||||
-rw-r--r-- | packages/integrations/mdx/src/utils.ts | 21 |
2 files changed, 38 insertions, 6 deletions
diff --git a/packages/integrations/mdx/src/index.ts b/packages/integrations/mdx/src/index.ts index bd3d50c86..7b4a24ff5 100644 --- a/packages/integrations/mdx/src/index.ts +++ b/packages/integrations/mdx/src/index.ts @@ -1,11 +1,13 @@ -import mdxPlugin from '@mdx-js/rollup'; import type { AstroIntegration } from 'astro'; +import mdxPlugin from '@mdx-js/rollup'; +import { parse as parseESM } from 'es-module-lexer'; +import { getFileInfo } from './utils.js'; export default function mdx(): AstroIntegration { return { name: '@astrojs/mdx', hooks: { - 'astro:config:setup': ({ updateConfig, addPageExtension, command }: any) => { + 'astro:config:setup': ({ updateConfig, config, addPageExtension, command }: any) => { addPageExtension('.mdx'); updateConfig({ vite: { @@ -20,14 +22,23 @@ export default function mdx(): AstroIntegration { mdExtensions: [], }), }, - command === 'dev' && { + { name: '@astrojs/mdx', transform(code: string, id: string) { if (!id.endsWith('.mdx')) return; - // TODO: decline HMR updates until we have a stable approach - return `${code}\nif (import.meta.hot) { + const [, moduleExports] = parseESM(code); + + if (!moduleExports.includes('url')) { + const { fileUrl } = getFileInfo(id, config); + code += `\nexport const url = ${JSON.stringify(fileUrl)};`; + } + if (command === 'dev') { + // TODO: decline HMR updates until we have a stable approach + code += `\nif (import.meta.hot) { import.meta.hot.decline(); - }`; + }` + } + return code; }, }, ], diff --git a/packages/integrations/mdx/src/utils.ts b/packages/integrations/mdx/src/utils.ts new file mode 100644 index 000000000..1091e8511 --- /dev/null +++ b/packages/integrations/mdx/src/utils.ts @@ -0,0 +1,21 @@ +import type { AstroConfig } from 'astro'; + +function appendForwardSlash(path: string) { + return path.endsWith('/') ? path : path + '/'; +} + +/** @see 'vite-plugin-utils' for source */ +export function getFileInfo(id: string, config: AstroConfig) { + const sitePathname = appendForwardSlash( + config.site ? new URL(config.base, config.site).pathname : config.base + ); + + const fileId = id.split('?')[0]; + let fileUrl = fileId.includes('/pages/') + ? fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, '') + : undefined; + if (fileUrl && config.trailingSlash === 'always') { + fileUrl = appendForwardSlash(fileUrl); + } + return { fileId, fileUrl }; +} |