0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-30 22:03:56 -05:00
astro/packages/integrations/mdx/src/index.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

147 lines
4.8 KiB
TypeScript
Raw Normal View History

2022-08-01 16:25:50 -05:00
import { compile as mdxCompile, nodeTypes } from '@mdx-js/mdx';
import mdxPlugin, { Options as MdxRollupPluginOptions } from '@mdx-js/rollup';
2022-08-05 18:58:09 -05:00
import type { AstroConfig, AstroIntegration } from 'astro';
import { parse as parseESM } from 'es-module-lexer';
2022-07-21 15:46:16 -05:00
import rehypeRaw from 'rehype-raw';
2022-07-20 20:36:26 -05:00
import remarkGfm from 'remark-gfm';
2022-07-21 15:46:16 -05:00
import remarkShikiTwoslash from 'remark-shiki-twoslash';
2022-07-20 20:36:26 -05:00
import remarkSmartypants from 'remark-smartypants';
2022-08-01 16:25:50 -05:00
import { VFile } from 'vfile';
2022-07-29 10:24:57 -05:00
import type { Plugin as VitePlugin } from 'vite';
2022-08-05 18:58:09 -05:00
import { rehypeApplyFrontmatterExport, remarkInitializeAstroData } from './astro-data-utils.js';
2022-08-01 16:25:50 -05:00
import rehypeCollectHeadings from './rehype-collect-headings.js';
import remarkPrism from './remark-prism.js';
import { getFileInfo, parseFrontmatter } from './utils.js';
MDX support (#3706) * feat: first pass at MDX support * fix: move built-in JSX renderer to come first * chore: remove jsx example * chore: update lockfile * chore: cleanup example * fix: missing deps * refactor: move component render logic to `renderPage` * chore: update HMR script * chore: update MDX example * refactor: prefer unshit * refactor: remove TODO comment * fix: remove duplicate identifier * refactor: cleanup mdx entrypoint * fix: better html handling * fix: add tsconfig to mdx package * chore: update lockfile * fix: do not sort plugins unless mdx is enabled * chore: update compiler * fix(hmr): maybe render head for non-Astro pages * fix: set initial pageExtensions * refactor: cleanup addPageExtension * refactor: remove addPageExtensions from types * refactor: expose HookParameters type * fix: only default to astro for MDX * test: pick up jsx support in test fixtures * refactor: simplify mdx entrypoint * test: add basic MDX tests * test(e2e): add mdx + framework tests * chore: update lockfile * test(e2e): fix preact mdx e2e test * fix(mdx): disable .md support * test(e2e): fix vue-component test missing mdx * test(e2e): fix solid component needing import * fix: allow `client:only="solid"` as an alias to `solid-js` * chore: move to with-mdx example * chore: update MDX readme * chore: update example readme * chore: bump astro version * chore: update lockfile * Update mod.d.ts * feat: support `export const components` in MDX pages * chore: update mdx example * fix: update jsx-runtime with better slot support * refactor: remove object style support * chore: cleanup package exports * chore: add todo comment * refactor: improve isPage function, move to utils * refactor: dry up manual HMR updates * chore: add dev tests for MDX * chore: prefer set to array * chore: add changesets * fix(hmr): flip public/private route Co-authored-by: Nate Moore <nate@astro.build>
2022-06-30 13:09:09 -05:00
type WithExtends<T> = T | { extends: T };
type MdxOptions = {
remarkPlugins?: WithExtends<MdxRollupPluginOptions['remarkPlugins']>;
rehypePlugins?: WithExtends<MdxRollupPluginOptions['rehypePlugins']>;
2022-07-20 20:36:26 -05:00
};
const DEFAULT_REMARK_PLUGINS: MdxRollupPluginOptions['remarkPlugins'] = [
remarkGfm,
remarkSmartypants,
];
const DEFAULT_REHYPE_PLUGINS: MdxRollupPluginOptions['rehypePlugins'] = [];
2022-07-21 15:46:16 -05:00
function handleExtends<T>(config: WithExtends<T[] | undefined>, defaults: T[] = []): T[] {
if (Array.isArray(config)) return config;
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.unshift([rehypeRaw, { passThrough: nodeTypes }]);
}
// getHeadings() is guaranteed by TS, so we can't allow user to override
rehypePlugins.unshift(rehypeCollectHeadings);
return rehypePlugins;
}
export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration {
MDX support (#3706) * feat: first pass at MDX support * fix: move built-in JSX renderer to come first * chore: remove jsx example * chore: update lockfile * chore: cleanup example * fix: missing deps * refactor: move component render logic to `renderPage` * chore: update HMR script * chore: update MDX example * refactor: prefer unshit * refactor: remove TODO comment * fix: remove duplicate identifier * refactor: cleanup mdx entrypoint * fix: better html handling * fix: add tsconfig to mdx package * chore: update lockfile * fix: do not sort plugins unless mdx is enabled * chore: update compiler * fix(hmr): maybe render head for non-Astro pages * fix: set initial pageExtensions * refactor: cleanup addPageExtension * refactor: remove addPageExtensions from types * refactor: expose HookParameters type * fix: only default to astro for MDX * test: pick up jsx support in test fixtures * refactor: simplify mdx entrypoint * test: add basic MDX tests * test(e2e): add mdx + framework tests * chore: update lockfile * test(e2e): fix preact mdx e2e test * fix(mdx): disable .md support * test(e2e): fix vue-component test missing mdx * test(e2e): fix solid component needing import * fix: allow `client:only="solid"` as an alias to `solid-js` * chore: move to with-mdx example * chore: update MDX readme * chore: update example readme * chore: bump astro version * chore: update lockfile * Update mod.d.ts * feat: support `export const components` in MDX pages * chore: update mdx example * fix: update jsx-runtime with better slot support * refactor: remove object style support * chore: cleanup package exports * chore: add todo comment * refactor: improve isPage function, move to utils * refactor: dry up manual HMR updates * chore: add dev tests for MDX * chore: prefer set to array * chore: add changesets * fix(hmr): flip public/private route Co-authored-by: Nate Moore <nate@astro.build>
2022-06-30 13:09:09 -05:00
return {
2022-06-30 13:11:12 -05:00
name: '@astrojs/mdx',
hooks: {
'astro:config:setup': ({ updateConfig, config, addPageExtension, command }: any) => {
2022-06-30 13:11:12 -05:00
addPageExtension('.mdx');
const mdxPluginOpts: MdxRollupPluginOptions = {
remarkPlugins: getRemarkPlugins(mdxOptions, config),
rehypePlugins: getRehypePlugins(mdxOptions, config),
jsx: true,
jsxImportSource: 'astro',
// Note: disable `.md` support
format: 'mdx',
mdExtensions: [],
};
2022-06-30 13:11:12 -05:00
updateConfig({
vite: {
plugins: [
{
enforce: 'pre',
...mdxPlugin(mdxPluginOpts),
// Override transform to alter code before MDX compilation
// ex. inject layouts
async transform(code, id) {
if (!id.endsWith('mdx')) return;
const { data: frontmatter, content: pageContent } = parseFrontmatter(code, id);
const compiled = await mdxCompile(new VFile({ value: pageContent, path: id }), {
...mdxPluginOpts,
rehypePlugins: [
...(mdxPluginOpts.rehypePlugins ?? []),
() => rehypeApplyFrontmatterExport(frontmatter),
],
});
return {
code: String(compiled.value),
map: compiled.map,
};
2022-07-29 10:24:57 -05:00
},
2022-06-30 13:11:12 -05:00
},
{
name: '@astrojs/mdx-postprocess',
// These transforms must happen *after* JSX runtime transformations
transform(code, id) {
2022-06-30 13:11:12 -05:00
if (!id.endsWith('.mdx')) return;
const [, moduleExports] = parseESM(code);
const { fileUrl, fileId } = getFileInfo(id, config);
if (!moduleExports.includes('url')) {
code += `\nexport const url = ${JSON.stringify(fileUrl)};`;
}
if (!moduleExports.includes('file')) {
code += `\nexport const file = ${JSON.stringify(fileId)};`;
}
if (command === 'dev') {
// TODO: decline HMR updates until we have a stable approach
code += `\nif (import.meta.hot) {
MDX support (#3706) * feat: first pass at MDX support * fix: move built-in JSX renderer to come first * chore: remove jsx example * chore: update lockfile * chore: cleanup example * fix: missing deps * refactor: move component render logic to `renderPage` * chore: update HMR script * chore: update MDX example * refactor: prefer unshit * refactor: remove TODO comment * fix: remove duplicate identifier * refactor: cleanup mdx entrypoint * fix: better html handling * fix: add tsconfig to mdx package * chore: update lockfile * fix: do not sort plugins unless mdx is enabled * chore: update compiler * fix(hmr): maybe render head for non-Astro pages * fix: set initial pageExtensions * refactor: cleanup addPageExtension * refactor: remove addPageExtensions from types * refactor: expose HookParameters type * fix: only default to astro for MDX * test: pick up jsx support in test fixtures * refactor: simplify mdx entrypoint * test: add basic MDX tests * test(e2e): add mdx + framework tests * chore: update lockfile * test(e2e): fix preact mdx e2e test * fix(mdx): disable .md support * test(e2e): fix vue-component test missing mdx * test(e2e): fix solid component needing import * fix: allow `client:only="solid"` as an alias to `solid-js` * chore: move to with-mdx example * chore: update MDX readme * chore: update example readme * chore: bump astro version * chore: update lockfile * Update mod.d.ts * feat: support `export const components` in MDX pages * chore: update mdx example * fix: update jsx-runtime with better slot support * refactor: remove object style support * chore: cleanup package exports * chore: add todo comment * refactor: improve isPage function, move to utils * refactor: dry up manual HMR updates * chore: add dev tests for MDX * chore: prefer set to array * chore: add changesets * fix(hmr): flip public/private route Co-authored-by: Nate Moore <nate@astro.build>
2022-06-30 13:09:09 -05:00
import.meta.hot.decline();
2022-07-20 09:58:33 -05:00
}`;
}
return code;
2022-06-30 13:11:12 -05:00
},
},
] as VitePlugin[],
2022-06-30 13:11:12 -05:00
},
});
},
},
};
MDX support (#3706) * feat: first pass at MDX support * fix: move built-in JSX renderer to come first * chore: remove jsx example * chore: update lockfile * chore: cleanup example * fix: missing deps * refactor: move component render logic to `renderPage` * chore: update HMR script * chore: update MDX example * refactor: prefer unshit * refactor: remove TODO comment * fix: remove duplicate identifier * refactor: cleanup mdx entrypoint * fix: better html handling * fix: add tsconfig to mdx package * chore: update lockfile * fix: do not sort plugins unless mdx is enabled * chore: update compiler * fix(hmr): maybe render head for non-Astro pages * fix: set initial pageExtensions * refactor: cleanup addPageExtension * refactor: remove addPageExtensions from types * refactor: expose HookParameters type * fix: only default to astro for MDX * test: pick up jsx support in test fixtures * refactor: simplify mdx entrypoint * test: add basic MDX tests * test(e2e): add mdx + framework tests * chore: update lockfile * test(e2e): fix preact mdx e2e test * fix(mdx): disable .md support * test(e2e): fix vue-component test missing mdx * test(e2e): fix solid component needing import * fix: allow `client:only="solid"` as an alias to `solid-js` * chore: move to with-mdx example * chore: update MDX readme * chore: update example readme * chore: bump astro version * chore: update lockfile * Update mod.d.ts * feat: support `export const components` in MDX pages * chore: update mdx example * fix: update jsx-runtime with better slot support * refactor: remove object style support * chore: cleanup package exports * chore: add todo comment * refactor: improve isPage function, move to utils * refactor: dry up manual HMR updates * chore: add dev tests for MDX * chore: prefer set to array * chore: add changesets * fix(hmr): flip public/private route Co-authored-by: Nate Moore <nate@astro.build>
2022-06-30 13:09:09 -05:00
}