Skip to content

Instantly share code, notes, and snippets.

@patrickarlt
Created November 14, 2019 22:09
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 patrickarlt/5b16e87e092ea9bf6b3413dba1180b21 to your computer and use it in GitHub Desktop.
Save patrickarlt/5b16e87e092ea9bf6b3413dba1180b21 to your computer and use it in GitHub Desktop.
const { read, write } = require("to-vfile");
const remark = require("remark");
const mdx = require("remark-mdx");
const visit = require("unist-util-visit");
const customPlugin = () => (tree, vfile) => {
vfile.data.plugin = "Set by custom plugin";
visit(tree, "heading", node => {
if (node.depth === 1) {
node.children = [{ type: "text", value: "Set by custom plugin" }];
}
});
};
(async () => {
const inPath = "./example.mdx";
const outPath = "./example-out.mdx";
// read input as vfile
const file = await read(inPath);
// Remark parser/stringify/processor using MDX plugin
const processor = remark()
.use(customPlugin)
.use(mdx);
// parse the MDX file into MDXAST
const tree = processor.parse(file.contents.toString());
// run any other transformer plugins against the MDXAST
const result = await processor.run(tree, file);
// stringify the result (remark-stringify)
const contents = await processor.stringify(result);
// write a vfile to disk
await write(
Object.assign({}, file, {
path: outPath,
contents
})
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment