diff options
author | 2022-08-05 18:55:38 -0500 | |
---|---|---|
committer | 2022-08-05 18:55:38 -0500 | |
commit | 2675b8633c5d5c45b237ec87940d5eaf1bfb1b4b (patch) | |
tree | 171d8ff13cb81ed038ac52dc34ed2a313ae78903 /packages/integrations/mdx/src/index.ts | |
parent | 4678a3f358840db853db55b753b329ae592a589c (diff) | |
download | astro-2675b8633c5d5c45b237ec87940d5eaf1bfb1b4b.tar.gz astro-2675b8633c5d5c45b237ec87940d5eaf1bfb1b4b.tar.zst astro-2675b8633c5d5c45b237ec87940d5eaf1bfb1b4b.zip |
Frontmatter injection for MD and MDX (#4176)
* feat: inject vfile data as exports
* feat: add vfile to renderMarkdown output
* feat: add safe astroExports parser to utils
* refactor: expose vite-plugin-utils on astro package
* feat: handle astroExports in mdx
* deps: vfile
* chore: lockfile
* test: astroExports in mdx
* refactor: merge plugin exports into forntmatter
* refactor: astroExports -> astro.frontmatter
* refactor: md astroExports -> astro.frontmatter
* feat: astro.frontmatter vite-plugin-markdown
* chore: remove unused import
* fix: inline safelyGetAstroData in MDX integration
* chore: check that frontmatter export is valid export name
* chore: error log naming
* test: mdx remark frontmatter injection
* fix: inconsistent shiki mod resolution
* fix: add new frontmatter and heading props
* test: remark vdata
* fix: spread astro.data.frontmatter
* test deps: mdast-util-to-string, reading-time
* fix: astro-md test package name
* test: md frontmatter injection
* fix: layouts
* deps: remove vite-plugin-utils export
* fix: package lock
* chore: remove dup import
* chore: changeset
* chore: add comment on safelyGetAstroData source
* deps: move mdast-util-to-string + reading-time to test fixture
* chore: move remark plugins to test fixture
* fix: override plugin frontmatter with user frontmatter
* test: md injected frontmatter overrides
* test: frontmatter injection overrides mdx
Diffstat (limited to 'packages/integrations/mdx/src/index.ts')
-rw-r--r-- | packages/integrations/mdx/src/index.ts | 110 |
1 files changed, 60 insertions, 50 deletions
diff --git a/packages/integrations/mdx/src/index.ts b/packages/integrations/mdx/src/index.ts index a7abb0c33..3b1ceaa4c 100644 --- a/packages/integrations/mdx/src/index.ts +++ b/packages/integrations/mdx/src/index.ts @@ -1,19 +1,18 @@ import { compile as mdxCompile, nodeTypes } from '@mdx-js/mdx'; import mdxPlugin, { Options as MdxRollupPluginOptions } from '@mdx-js/rollup'; -import type { AstroIntegration } from 'astro'; +import type { AstroIntegration, AstroConfig } from 'astro'; +import { remarkInitializeAstroData, rehypeApplyFrontmatterExport } from './astro-data-utils.js'; import { parse as parseESM } from 'es-module-lexer'; import rehypeRaw from 'rehype-raw'; -import remarkFrontmatter from 'remark-frontmatter'; import remarkGfm from 'remark-gfm'; import type { RemarkMdxFrontmatterOptions } from 'remark-mdx-frontmatter'; -import remarkMdxFrontmatter from 'remark-mdx-frontmatter'; import remarkShikiTwoslash from 'remark-shiki-twoslash'; import remarkSmartypants from 'remark-smartypants'; import { VFile } from 'vfile'; import type { Plugin as VitePlugin } from 'vite'; import rehypeCollectHeadings from './rehype-collect-headings.js'; import remarkPrism from './remark-prism.js'; -import { getFileInfo, getFrontmatter } from './utils.js'; +import { getFileInfo, parseFrontmatter } from './utils.js'; type WithExtends<T> = T | { extends: T }; @@ -37,44 +36,52 @@ function handleExtends<T>(config: WithExtends<T[] | undefined>, defaults: T[] = return [...defaults, ...(config?.extends ?? [])]; } +function getRemarkPlugins( + mdxOptions: MdxOptions, + config: AstroConfig +): MdxRollupPluginOptions['remarkPlugins'] { + let remarkPlugins = [ + // Initialize vfile.data.astroExports before all plugins are run + remarkInitializeAstroData, + ...handleExtends(mdxOptions.remarkPlugins, DEFAULT_REMARK_PLUGINS), + ]; + if (config.markdown.syntaxHighlight === 'shiki') { + // Default export still requires ".default" chaining for some reason + // Workarounds tried: + // - "import * as remarkShikiTwoslash" + // - "import { default as remarkShikiTwoslash }" + const shikiTwoslash = (remarkShikiTwoslash as any).default ?? remarkShikiTwoslash; + remarkPlugins.push([shikiTwoslash, config.markdown.shikiConfig]); + } + if (config.markdown.syntaxHighlight === 'prism') { + remarkPlugins.push(remarkPrism); + } + return remarkPlugins; +} + +function getRehypePlugins( + mdxOptions: MdxOptions, + config: AstroConfig +): MdxRollupPluginOptions['rehypePlugins'] { + let rehypePlugins = handleExtends(mdxOptions.rehypePlugins, DEFAULT_REHYPE_PLUGINS); + + if (config.markdown.syntaxHighlight === 'shiki' || config.markdown.syntaxHighlight === 'prism') { + rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]); + } + + return rehypePlugins; +} + export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration { return { name: '@astrojs/mdx', hooks: { 'astro:config:setup': ({ updateConfig, config, addPageExtension, command }: any) => { addPageExtension('.mdx'); - let remarkPlugins = handleExtends(mdxOptions.remarkPlugins, DEFAULT_REMARK_PLUGINS); - let rehypePlugins = handleExtends(mdxOptions.rehypePlugins, DEFAULT_REHYPE_PLUGINS); - - if (config.markdown.syntaxHighlight === 'shiki') { - remarkPlugins.push([ - // Default export still requires ".default" chaining for some reason - // Workarounds tried: - // - "import * as remarkShikiTwoslash" - // - "import { default as remarkShikiTwoslash }" - (remarkShikiTwoslash as any).default ?? remarkShikiTwoslash, - config.markdown.shikiConfig, - ]); - rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]); - } - - if (config.markdown.syntaxHighlight === 'prism') { - remarkPlugins.push(remarkPrism); - rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]); - } - - remarkPlugins.push(remarkFrontmatter); - remarkPlugins.push([ - remarkMdxFrontmatter, - { - name: 'frontmatter', - ...mdxOptions.frontmatterOptions, - }, - ]); const mdxPluginOpts: MdxRollupPluginOptions = { - remarkPlugins, - rehypePlugins, + remarkPlugins: getRemarkPlugins(mdxOptions, config), + rehypePlugins: getRehypePlugins(mdxOptions, config), jsx: true, jsxImportSource: 'astro', // Note: disable `.md` support @@ -93,24 +100,27 @@ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration { async transform(code, id) { if (!id.endsWith('mdx')) return; - // If user overrides our default YAML parser, - // do not attempt to parse the `layout` via gray-matter - if (!mdxOptions.frontmatterOptions?.parsers) { - const frontmatter = getFrontmatter(code, id); - if (frontmatter.layout) { - const { layout, ...content } = frontmatter; - code += `\n\nexport default async function({ children }) {\nconst Layout = (await import(${JSON.stringify( - frontmatter.layout - )})).default;\nconst frontmatter=${JSON.stringify( - content - )};\nreturn <Layout frontmatter={frontmatter} content={frontmatter} headings={getHeadings()}>{children}</Layout> }`; - } + let { data: frontmatter, content: pageContent } = parseFrontmatter(code, id); + if (frontmatter.layout) { + const { layout, ...contentProp } = frontmatter; + pageContent += `\n\nexport default async function({ children }) {\nconst Layout = (await import(${JSON.stringify( + frontmatter.layout + )})).default;\nconst frontmatter=${JSON.stringify( + contentProp + )};\nreturn <Layout frontmatter={frontmatter} content={frontmatter} headings={getHeadings()}>{children}</Layout> }`; } - const compiled = await mdxCompile( - new VFile({ value: code, path: id }), - mdxPluginOpts - ); + const compiled = await mdxCompile(new VFile({ value: pageContent, path: id }), { + ...mdxPluginOpts, + rehypePlugins: [ + ...(mdxPluginOpts.rehypePlugins ?? []), + () => + rehypeApplyFrontmatterExport( + frontmatter, + mdxOptions.frontmatterOptions?.name + ), + ], + }); return { code: String(compiled.value), |