Add class to mdast-util-to-hast
#40
-
As said here, I'm trying to add class to Here's my markup: const toHast = require('mdast-util-to-hast')
const toHtml = require('hast-util-to-html')
switch (l.type) {
case 'inlineCode': {
return toHtml(
toHast(l, {
handlers: {
code: (h, node) => {
let props = {}
props.className =
'p-1 overflow-x-auto text-base bg-gray-900 rounded-md text-blue-gray-200'
return h(node, 'code', props)
},
},
})
)
default:
return toHtml(toHast(l)) // this works without trying to add handler
} This doesn't work. Am I doing it right or is there any other way to add class to I did find rehype-add-classes however I'm not getting how to use it in combination with const unified = require('unified')
const toHast = require('mdast-util-to-hast')
const toHtml = require('hast-util-to-html')
const addClasses = require('rehype-add-classes')
switch (l.type) {
case 'inlineCode': {
return unified().use(toHast(l)).use(toHtml).use(addClasses, {
code:
'p-1 overflow-x-auto text-base bg-gray-900 rounded-md text-blue-gray-200',
})
}
default:
return toHtml(toHast(l))
} I am not understanding how to do |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
This is not the venue to talk about mdast or hast. This is micromark: a low-level project that you are not dealing with. It might be good to take a step back and read up on what unified is? https://unifiedjs.com/learn/ mdast is markdown. hast is html. Classes are an HTML thing, so I don’t think there’s a need to do anything in mdast space |
Beta Was this translation helpful? Give feedback.
-
Wow, that new code worked too. I'll post the answer here for quick access: rehype/add-classes.js// Thanks @wooorm -> https://github.com/micromark/micromark/discussions/40#discussioncomment-141871
const selectAll = require('hast-util-select').selectAll
const classnames = require('hast-util-classnames')
function rehypeClasses(options) {
return transform
function transform(tree) {
let selector
let index
for (selector in options) {
nodes = selectAll(selector, tree)
index = -1
while (++index < nodes.length) {
classnames(nodes[index], options[selector])
}
}
}
}
module.exports = rehypeClasses next.config.jsconst mdx = [
options.defaultLoaders.babel,
{
loader: '@mdx-js/loader',
options: {
remarkPlugins: [withCodeSamples, withSyntaxHighlighting, table, list],
rehypePlugins: [
[
addClasses,
{
code: 'p-1 overflow-x-auto text-base bg-gray-900 rounded-md text-blue-gray-200',
},
],
],
},
},
] |
Beta Was this translation helpful? Give feedback.
Wow, that new code worked too. I'll post the answer here for quick access:
rehype/add-classes.js
next.config.js