Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created July 9, 2021 21:40
Show Gist options
  • Save kentcdodds/ee3569fdccd43c2a51228c6be274dfb6 to your computer and use it in GitHub Desktop.
Save kentcdodds/ee3569fdccd43c2a51228c6be274dfb6 to your computer and use it in GitHub Desktop.
Parsing HTML or Markdown and processing both as markdown then outputting to HTML
const unified = require('unified')
const parseMarkdown = require('remark-parse')
const parseHtml = require('rehype-parse')
const remark2rehype = require('remark-rehype')
const rehype2remark = require('rehype-remark')
const rehypeStringify = require('rehype-stringify')
const visit = require('unist-util-visit')
async function go() {
const inputString = `
<div><p><h3>Hello</h3> <strong>world</strong></p></div>
`
const isHTMLInput = inputString.trim().startsWith('<')
const {contents} = await unified()
.use(isHTMLInput ? parseHtml : parseMarkdown)
.use(isHTMLInput ? rehype2remark : () => {})
.use(function logHeadings() {
// this is where I'll put my plugin stuff... just logging for now
return function transformer(root, file) {
visit(root, 'heading', node => {
console.log(node.depth, node.children[0].value)
})
}
})
.use(remark2rehype)
.use(rehypeStringify)
.process(inputString)
console.log(contents.toString())
}
go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment