@unifast/react

將 unifast 的 HAST 輸出轉換為 React 元素,並支援元件對應

概觀

@unifast/react 會將 unifast 的 HAST(HTML Abstract Syntax Tree)輸出轉換為 React 元素。它提供兩個主要的函式:

本套件會自動處理 HTML 屬性與 React prop 名稱的對應(例如將 class 轉為 classNamefor 轉為 htmlFor 等),並解析 CSS style 字串。

安裝

對等相依套件:使用 compileToReact 時需要 @unifast/node

型別定義

CompileToReactOptions

繼承 CompileOptions,並加入 React 專屬欄位。

屬性型別說明
createElementCreateElementReact 的 createElement 函式
FragmentunknownReact 的 Fragment 元件
components?ComponentMapHTML 標籤名稱到 React 元件的對應表
(所有 CompileOptions)-繼承自 CompileOptions

CompileToReactResult

屬性型別說明
elementunknown根 React 元素
frontmatterRecord<string, unknown>已解析的 frontmatter 後設資料
diagnosticsDiagnostic[]警告與錯誤
stats{ parseMs, transformMs, emitMs }各階段耗時(毫秒)
tocTocEntry[]擷取而得的目錄

HastToReactOptions

屬性型別說明
createElementCreateElementReact 的 createElement 函式
FragmentunknownReact 的 Fragment 元件
components?ComponentMapHTML 標籤名稱到自訂 React 元件的對應表

CreateElement

type CreateElement = (type: any, props: any, ...children: any[]) => any;

ComponentMap

type ComponentMap = Record<string, unknown>;

屬性名稱轉換

HTML 屬性React Prop
classclassName
forhtmlFor
accesskeyaccessKey
autocompleteautoComplete
autofocusautoFocus
autoplayautoPlay
charsetcharSet
colspancolSpan
contenteditablecontentEditable
crossorigincrossOrigin
datetimedateTime
enctypeencType
formactionformAction
hreflanghrefLang
httpequivhttpEquiv
inputmodeinputMode
maxlengthmaxLength
minlengthminLength
novalidatenoValidate
readonlyreadOnly
referrerpolicyreferrerPolicy
rowspanrowSpan
spellcheckspellCheck
srcdocsrcDoc
srclangsrcLang
srcsetsrcSet
tabindextabIndex
usemapuseMap

CSS style 字串會自動解析為 React style 物件(例如 "font-size: 16px" 會變成 { fontSize: "16px" })。

匯出列表

匯出名稱類別說明
compileToReactfunction將 Markdown/MDX 編譯為 React 元素
hastToReactfunction將 HAST 轉換為 React 元素
CompileToReactOptionstypecompileToReact 的選項
CompileToReactResulttypecompileToReact 的結果
HastToReactOptionstypehastToReact 的選項
CreateElementtypeReact createElement 函式簽名
ComponentMaptypeHTML 標籤至元件的對應表