Process markdown with remark-html
Basically, when you import a .md
file, you'll get back a JS module with an HTML string as its default export. There are various options to customize the HTML output.
import remarkHtml from 'vite-remark-html'
export default {
plugins: [remarkHtml()],
}
To add Remark plugins, call the use
method on the Vite plugin. It returns the Vite plugin, so you can easily chain together multiple .use
calls.
import remarkHtml from 'vite-remark-html'
import remarkSlug from 'remark-slug'
export default {
plugins: [remarkHtml().use(remarkSlug)],
}
Markdown files can be filtered, in case you only want a subset to be processed by this plugin.
remarkHtml({
exclude: /\/node_modules\//,
})
For more details, see here.
All options listed here are also supported.
remarkHtml({
allowDangerousHtml: true,
})
In your client code, you can use import
or dynamic import()
to load the HTML string.
import html from './test.md'
// or
const htmlPromise = import('./test.md').then(module => module.default)
Then you can use that as the innerHTML
of another element.
document.getElementById('markdown').innerHTML = html
// or
<div dangerouslySetInnerHtml={{ __html: html }} />
Try the demo to see it in action.
In your tsconfig.json
{
"compilerOptions": {
"types": ["vite-remark-html/client"]
}
}
This lets you import .md
files with type-checking support.