The Node.js® Website
1'use strict';
2
3import { evaluate } from '@mdx-js/mdx';
4import { Fragment, jsx, jsxs } from 'react/jsx-runtime';
5import { matter } from 'vfile-matter';
6
7import { NEXT_REHYPE_PLUGINS, NEXT_REMARK_PLUGINS } from './next.mdx.mjs';
8import { createGitHubSlugger } from './util/gitHubUtils';
9
10// Defines the React Runtime Components
11const reactRuntime = { Fragment, jsx, jsxs };
12
13/**
14 * This is our custom simple MDX Compiler that is used to compile Markdown and MDX
15 * this returns a serializable VFile as a string that then gets passed to our MDX Provider
16 *
17 * @param {import('vfile').VFile} source
18 * @param {'md' | 'mdx'} fileExtension
19 * @returns {Promise<{
20 * MDXContent: import('mdx/types').MDXContent;
21 * headings: Array<import('@vcarl/remark-headings').Heading>;
22 * frontmatter: Record<string, any>;
23 * readingTime: import('reading-time').ReadTimeResults;
24 * }>}
25 */
26export async function compileMDX(source, fileExtension) {
27 // Parses the Frontmatter to the VFile and removes from the original source
28 // cleaning the frontmatter to the source that is going to be parsed by the MDX Compiler
29 matter(source, { strip: true });
30
31 const slugger = createGitHubSlugger();
32
33 // This is a minimal MDX Compiler that is lightweight and only parses the MDX
34 const { default: MDXContent } = await evaluate(source, {
35 rehypePlugins: NEXT_REHYPE_PLUGINS,
36 remarkPlugins: NEXT_REMARK_PLUGINS,
37 format: fileExtension,
38 baseUrl: import.meta.url,
39 ...reactRuntime,
40 });
41
42 // Retrieve some parsed data from the VFile metadata
43 // such as frontmatter and Markdown headings
44 const { headings, matter: frontmatter, readingTime } = source.data;
45
46 headings.forEach(heading => {
47 // we re-sluggify the links to match the GitHub slugger
48 // since some also do not come with sluggifed links
49 heading.data = { ...heading.data, id: slugger(heading.value) };
50 });
51
52 return { MDXContent, headings, frontmatter, readingTime };
53}