Closed9
MDXを触ってみる

やりたいこと
現状自分のブログの記事はマークダウンで書いているが、マークダウンファイルにJSXを埋め込みたい
どうやらMDXというものがあるらしいじゃないか

import fs from 'node:fs/promises'
import {compile} from '@mdx-js/mdx'
const compiled = await compile(await fs.readFile('example.mdx'))
console.log(String(compiled))
公式より。
これでmdx(JSX入りのマークダウン) => HTMLにできるのか?

いや、Compile MDX to JS.
って書いてあるな
compile(file, options?)
こう書いてあるが文字列とかも渡せるらしい

input.mdx
export function Thing() {
return <>World</>
}
# Hello <Thing />
これが
output.jsx
/* @jsxRuntime automatic */
/* @jsxImportSource react */
export function Thing() {
return <>World</>
}
export default function MDXContent() {
return <h1>Hello <Thing /></h1>
}
これに変換されるらしい

↑これはイメージで実際は
import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime'
export function Thing() {
return _jsx(_Fragment, {children: 'World'})
}
function _createMdxContent(props) {
const _components = {h1: 'h1', ...props.components}
return _jsxs(_components.h1, {children: ['Hello ', _jsx(Thing, {})]})
}
export default function MDXContent(props = {}) {
const {wrapper: MDXLayout} = props.components || {}
return MDXLayout
? _jsx(MDXLayout, {...props, children: _jsx(_createMdxContent, {...props})})
: _createMdxContent(props)
}
こんな感じらしい

めっちゃこれかも

これコンパイルしたやつをどうレンダリングすればええんや

MDX形式の文字列をレンダリングしたい。出力がJSXファイルなのがめんどくさいな

これでやりたいことができた
このスクラップは2024/06/06にクローズされました