-
MDX 2 introduces parsing md inside html, but afaiu it seems to not work correctly with rehype plugins. You'll understand better with a reproduction... import { compile } from '@mdx-js/mdx'
import rehypeShiki from "@leafac/rehype-shiki"
import shiki from "shiki"
const test = async src => String(await compile(src, {
rehypePlugins: [
[rehypeShiki, {
highlighter: await shiki.getHighlighter({ theme: "github-light" })
}]
]
}))
console.log("// --- TEST 1 " + "-".repeat(30))
console.log(await test(`
\`\`\`js
let hello = "world"
\`\`\`
`))
console.log("\n")
console.log("// --- TEST 2 " + "-".repeat(30))
console.log(await test(`
<div>
\`\`\`js
let hello = "world"
\`\`\`
</div>
`)) Output
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
That, uhm, points at the most likely problem? If you can’t get a project to work in different examples, then maybe the problem is that project. I’m guessing that this logic they have is way too strict and doesn’t account for |
Beta Was this translation helpful? Give feedback.
-
An update: The problem was that the plugin traverses only root's children and not the whole tree. So it can be solved by simply traversing the whole tree, I thought it would be trivial to do that with import shiki from "shiki"
import { unified } from "unified"
import { visit } from "unist-util-visit"
import rehypeParse from "rehype-parse"
const themes = ["github-light", "github-dark"]
export default () => async tree => {
let highlighter = await shiki.getHighlighter({ themes })
visit(tree, (node, index, parent) => {
if (!(
node.tagName === "pre" &&
node.children?.[0]?.tagName === "code" &&
node.children?.[0]?.properties?.className?.[0].startsWith("language-") &&
node.children?.[0]?.children?.[0]?.type === "text"
)) return
let code = node.children[0].children[0].value
let lang = node.children[0].properties.className[0].slice("language-".length)
parent.children.splice(
index,
1,
...themes.map(theme => {
let n =
unified()
.use(rehypeParse, { fragment: true })
.parse(highlighter.codeToHtml(code, { theme, lang }))
n.children[0].properties.className.push(theme)
return n
})
)
})
} |
Beta Was this translation helpful? Give feedback.
That, uhm, points at the most likely problem? If you can’t get a project to work in different examples, then maybe the problem is that project.
I verified that by trying another highlighters (
rehype-highlight
), which did work.I’m guessing that this logic they have is way too strict and doesn’t account for
<pre>
s in<div>
s.