Skip to content

Instantly share code, notes, and snippets.

@y-nk
Created February 6, 2022 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save y-nk/c55d74095f47a0a124099b739cceb388 to your computer and use it in GitHub Desktop.
Save y-nk/c55d74095f47a0a124099b739cceb388 to your computer and use it in GitHub Desktop.
import { parse as parseAst } from "acorn";
import { load as parseYaml } from "js-yaml";
import { parse as parseToml } from "toml";
// stolen from remcohaszing/remark-mdx-frontmatter
const getValue = (node) => {
const { type, value } = node;
if (type === "yaml") {
return load(value);
} else if (node.type === "toml") {
return parse(value);
}
};
// the idea is to trust the people not to be stupid about it.
// another possible returned value could be:
// `MDXContent.frontmatterData = ${JSON.stringify(data)}`
const defaultRenderer = (data, node) => {
return `
export const getStaticProps = async () => {
return { props: ${JSON.stringify(data)} }
}
`;
};
// eslint-disable-next-line import/no-anonymous-default-export
export default (renderer = defaultRenderer) =>
(ast) => {
const metadata = [];
ast.children = ast.children.map((node) => {
const data = getValue(node);
if (!data) return node;
// we help the common mogul not to deal with ast.
// let them create a valid stringified javascript
// representation of what they want, and inject
// back the correctly parsed tree into the ast
const renderedString = renderer(data, node);
const { body } = parseAst(renderedString, { sourceType: "module" });
return {
type: "mdxjsEsm",
data: {
estree: {
type: "Program",
sourceType: "module",
body,
},
},
};
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment