Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork4
hast utility to transform to preact, react, solid, svelte, vue, etc
License
syntax-tree/hast-util-to-jsx-runtime
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
hast utility to transform a tree topreact, react, solid, svelte, vue, etcetera,with an automatic JSX runtime.
- What is this?
- When should I use this?
- Install
- Use
- API
- Errors
- Examples
- Syntax
- Compatibility
- Security
- Related
- Contribute
- License
This package is a utility that takes ahast tree and anautomatic JSX runtime and turns the tree into anythingyou wish.
You can use this package when you have a hast syntax tree and want to use itwith whatever framework.
This package uses an automatic JSX runtime,which is a sort of lingua franca for frameworks to support JSX.
Notably,automatic runtimes have support for passing extra information in development,and have guaranteed support for fragments.
This package isESM only.In Node.js (version 16+),install withnpm:
npm install hast-util-to-jsx-runtime
In Deno withesm.sh:
import{toJsxRuntime}from'https://esm.sh/hast-util-to-jsx-runtime@2'
In browsers withesm.sh:
<scripttype="module">import{toJsxRuntime}from'https://esm.sh/hast-util-to-jsx-runtime@2?bundle'</script>
import{h}from'hastscript'import{toJsxRuntime}from'hast-util-to-jsx-runtime'import{Fragment,jsxs,jsx}from'react/jsx-runtime'import{renderToStaticMarkup}from'react-dom/server'consttree=h('h1','Hello, world!')constdoc=renderToStaticMarkup(toJsxRuntime(tree,{Fragment, jsxs, jsx}))console.log(doc)
Yields:
<h1>Hello, world!</h1>
Note:to add better type support,register a global JSX namespace:
importtype{JSXasJsx}from'react/jsx-runtime'declare global{namespaceJSX{typeElementClass=Jsx.ElementClasstypeElement=Jsx.ElementtypeIntrinsicElements=Jsx.IntrinsicElements}}
This package exports the identifiertoJsxRuntime.It exports theTypeScript typesComponents,CreateEvaluater,ElementAttributeNameCase,EvaluateExpression,EvaluateProgram,Evaluater,ExtraProps,Fragment,Jsx,JsxDev,Options,Props,Source,Space,andStylePropertyNameCase.There is no default export.
Transform a hast tree topreact, react, solid, svelte, vue, etcetera,with an automatic JSX runtime.
Result from your configured JSX runtime(JSX.Element if defined,otherwiseunknown which you can cast yourself).
Possible components to use (TypeScript type).
Each key is a tag name typed inJSX.IntrinsicElements,if defined.Each value is either a different tag nameor a component accepting the corresponding props(and an optionalnode prop ifpassNode is on).
You can access props atJSX.IntrinsicElements.For example,to find props fora,useJSX.IntrinsicElements['a'].
importtype{Element}from'hast'typeExtraProps={node?:Element|undefined}typeComponents={[TagNameinkeyofJSX.IntrinsicElements]:|Component<JSX.IntrinsicElements[TagName]&ExtraProps>|keyofJSX.IntrinsicElements}typeComponent<ComponentProps>=// Class component:|(new(props:ComponentProps)=>JSX.ElementClass)// Function component:|((props:ComponentProps)=>JSX.Element|string|null|undefined)
Create an evaluator that turns ESTree ASTs from embedded MDX into values(TypeScript type).
There are no parameters.
Evaluater (Evaluater).
Casing to use for attribute names (TypeScript type).
HTML casing is for exampleclass,stroke-linecap,xml:lang.React casing is for exampleclassName,strokeLinecap,xmlLang.
typeElementAttributeNameCase='html'|'react'
Turn an MDX expression into a value (TypeScript type).
expression(Expressionfrom@types/estree)— estree expression
Result of expression (unknown).
Turn an MDX program (export/import statements) into a value (TypeScript type).
program(Programfrom@types/estree)— estree program
Result of program (unknown);should likely beundefined as ESM changes the scope but doesn’t yieldsomething.
Evaluator that turns ESTree ASTs from embedded MDX into values (TypeScripttype).
evaluateExpression(EvaluateExpression)— evaluate an expressionevaluateProgram(EvaluateProgram)— evaluate a program
Extra fields we pass (TypeScript type).
typeExtraProps={node?:Element|undefined}
Represent the children,typically a symbol (TypeScript type).
typeFragment=unknown
Create a production element (TypeScript type).
type(unknown)— element type:Fragmentsymbol,tag name (string),componentprops(Props)— element props,children,and maybenodekey(stringorundefined)— dynamicly generated key to use
Element from your framework(JSX.Element if defined,otherwiseunknown which you can cast yourself).
Create a development element (TypeScript type).
type(unknown)— element type:Fragmentsymbol,tag name (string),componentprops(Props)— element props,children,and maybenodekey(stringorundefined)— dynamicly generated key to useisStaticChildren(boolean)— whether two or more children are passed (in an array),which is whetherjsxsorjsxwould be usedsource(Source)— info about sourceself(undefined)— nothing (this is used by frameworks that have components,we don’t)
Element from your framework(JSX.Element if defined,otherwiseunknown which you can cast yourself).
Configuration (TypeScript type).
Fragment(Fragment, required)— fragmentjsxDEV(JsxDev, required in development)— development JSXjsxs(Jsx, required in production)— static JSXjsx(Jsx, required in production)— dynamic JSXcomponents(Partial<Components>, optional)— components to usecreateEvaluater(CreateEvaluater, optional)— create an evaluator that turns ESTree ASTs into valuesdevelopment(boolean, default:false)— whether to usejsxDEVwhen on orjsxandjsxswhen offelementAttributeNameCase(ElementAttributeNameCase,default:'react')— specify casing to use for attribute namesfilePath(string, optional)— file path to the original source file,passed in source info tojsxDEVwhen using the automatic runtime withdevelopment: truepassNode(boolean, default:false)— pass the hast element node to componentsspace(Space, default:'html')— whethertreeis in the'html'or'svg'space, when an<svg>element is found in the HTML space,this package already automatically switches to and from the SVG space whenentering and exiting itstylePropertyNameCase(StylePropertyNameCase,default:'dom')— specify casing to use for property names instyleobjectstableCellAlignToStyle(boolean, default:true)— turn obsoletealignprops ontdandthinto CSSstyleprops
Properties and children (TypeScript type).
importtype{Element}from'hast'typeProps={[prop:string]:|Array<JSX.Element|string|null|undefined>// For `children`.|Record<string,string>// For `style`.|Element// For `node`.|boolean|number|string|undefinedchildren:Array<JSX.Element|string|null|undefined>|undefinednode?:Element|undefined}
Info about source (TypeScript type).
columnNumber(numberorundefined)— column where thing starts (0-indexed)fileName(stringorundefined)— name of source filelineNumber(numberorundefined)— line where thing starts (1-indexed)
Namespace (TypeScript type).
👉Note:hast is not XML;it supports SVG as embedded in HTML;it does not support the features available in XML;passing SVG might break but fragments of modern SVG should be fine;use
xastif you need to support SVG as XML.
typeSpace='html'|'svg'
Casing to use for property names instyle objects (TypeScript type).
CSS casing is for examplebackground-color and-webkit-line-clamp.DOM casing is for examplebackgroundColor andWebkitLineClamp.
typeStylePropertyNameCase='css'|'dom'
The following errors are thrown:
This error is thrown when eitheroptions is not passed at all orwhenoptions.Fragment isundefined.
The automatic JSX runtime needs a symbol for a fragment to work.
To solve the error,make sure you are passing the correct fragment symbol from your framework.
This error is thrown whenoptions.development is turned on (true),but whenoptions.jsxDEV is not a function.
The automatic JSX runtime,in development,needs this function.
To solve the error,make sure you are importing the correct runtime functions(for example,'react/jsx-dev-runtime'),and passjsxDEV.
These errors are thrown whenoptions.development isnot turned on(false or not defined),and whenoptions.jsx oroptions.jsxs are not functions.
The automatic JSX runtime,in production,needs these functions.
To solve the error,make sure you are importing the correct runtime functions(for example,'react/jsx-runtime'),and passjsx andjsxs.
This error is thrown when MDX nodes are passed that represent JavaScriptprograms or expressions.
Supporting JavaScript can be unsafe and requires a different project.To support JavaScript,pass acreateEvaluater function inoptions.
This error is thrown when astyle attribute is found on an element,which cannot be parsed as CSS.
Most frameworks don’t acceptstyle as a string,so we need to parse it as CSS,and pass it as an object.But when broken CSS is used,such asstyle="color:red; /*",we crash.
To solve the error,make sure authors write valid CSS.Alternatively,passoptions.ignoreInvalidStyle: true to swallow these errors.
👉Note:you must set
elementAttributeNameCase: 'html'for preact.
In Node.js,do:
import{h}from'hastscript'import{toJsxRuntime}from'hast-util-to-jsx-runtime'import{Fragment,jsx,jsxs}from'preact/jsx-runtime'import{render}from'preact-render-to-string'constresult=render(toJsxRuntime(h('h1','hi!'),{ Fragment, jsx, jsxs,elementAttributeNameCase:'html'}))console.log(result)
Yields:
<h1>hi!</h1>
In a browser,do:
import{h}from'https://esm.sh/hastscript@9'import{toJsxRuntime}from'https://esm.sh/hast-util-to-jsx-runtime@2'import{Fragment,jsx,jsxs}from'https://esm.sh/preact@10/jsx-runtime'import{render}from'https://esm.sh/preact@10'render(toJsxRuntime(h('h1','hi!'),{ Fragment, jsx, jsxs,elementAttributeNameCase:'html'}),document.getElementById('root'))
To add better type support,register a global JSX namespace:
importtype{JSXasJsx}from'preact/jsx-runtime'declare global{namespaceJSX{typeElementClass=Jsx.ElementClasstypeElement=Jsx.ElementtypeIntrinsicElements=Jsx.IntrinsicElements}}
👉Note:you must set
elementAttributeNameCase: 'html'andstylePropertyNameCase: 'css'for Solid.
In Node.js,do:
import{h}from'hastscript'import{toJsxRuntime}from'hast-util-to-jsx-runtime'import{Fragment,jsx,jsxs}from'solid-jsx/jsx-runtime'console.log(toJsxRuntime(h('h1','hi!'),{ Fragment, jsx, jsxs,elementAttributeNameCase:'html',stylePropertyNameCase:'css'}).t)
Yields:
<h1>hi!</h1>
In a browser,do:
import{h}from'https://esm.sh/hastscript@9'import{toJsxRuntime}from'https://esm.sh/hast-util-to-jsx-runtime@2'import{Fragment,jsx,jsxs}from'https://esm.sh/solid-js@1/h/jsx-runtime'import{render}from'https://esm.sh/solid-js@1/web'render(Component,document.getElementById('root'))functionComponent(){returntoJsxRuntime(h('h1','hi!'),{ Fragment, jsx, jsxs,elementAttributeNameCase:'html',stylePropertyNameCase:'css'})}
To add better type support,register a global JSX namespace:
importtype{JSXasJsx}from'solid-js/jsx-runtime'declare global{namespaceJSX{typeElementClass=Jsx.ElementClasstypeElement=Jsx.ElementtypeIntrinsicElements=Jsx.IntrinsicElements}}
I have no clue how to render a Svelte component in Node,but you can get that component with:
import{h}from'hastscript'import{toJsxRuntime}from'hast-util-to-jsx-runtime'import{Fragment,jsx,jsxs}from'svelte-jsx'constsvelteComponent=toJsxRuntime(h('h1','hi!'),{Fragment, jsx, jsxs})console.log(svelteComponent)
Yields:
[class Component extends SvelteComponent]Types for Svelte are broken.Raise it with Svelte.
👉Note:you must set
elementAttributeNameCase: 'html'for Vue.
In Node.js,do:
importserverRendererfrom'@vue/server-renderer'import{h}from'hastscript'import{toJsxRuntime}from'hast-util-to-jsx-runtime'import{Fragment,jsx,jsxs}from'vue/jsx-runtime'// Available since `vue@3.3`.console.log(awaitserverRenderer.renderToString(toJsxRuntime(h('h1','hi!'),{ Fragment, jsx, jsxs,elementAttributeNameCase:'html'})))
Yields:
<h1>hi!</h1>
In a browser,do:
import{h}from'https://esm.sh/hastscript@9'import{toJsxRuntime}from'https://esm.sh/hast-util-to-jsx-runtime@2'import{createApp}from'https://esm.sh/vue@3'import{Fragment,jsx,jsxs}from'https://esm.sh/vue@3/jsx-runtime'createApp(Component).mount('#root')functionComponent(){returntoJsxRuntime(h('h1','hi!'),{ Fragment, jsx, jsxs,elementAttributeNameCase:'html'})}
To add better type support,register a global JSX namespace:
importtype{JSXasJsx}from'vue/jsx-runtime'declare global{namespaceJSX{typeElementClass=Jsx.ElementClasstypeElement=Jsx.ElementtypeIntrinsicElements=Jsx.IntrinsicElements}}
HTML is parsed according to WHATWG HTML (the living standard),which is also followed by browsers such as Chrome,Firefox,and Safari.
Projects maintained by the unified collective are compatible with maintainedversions of Node.js.
When we cut a new major release,we drop support for unmaintained versions of Node.This means we try to keep the current release line,hast-util-to-jsx-runtime@2,compatible with Node.js 16.
Be careful with user input in your hast tree.Usehast-util-santize to make hast trees safe.
hastscript— build hast treeshast-util-to-html— serialize hast as HTMLhast-util-sanitize— sanitize hast
Seecontributing.mdinsyntax-tree/.githubfor ways to get started.Seesupport.md for ways to get help.
This project has acode of conduct.By interacting with this repository,organization,or community you agree to abide by its terms.
About
hast utility to transform to preact, react, solid, svelte, vue, etc
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.