Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

hast utility to transform to preact, react, solid, svelte, vue, etc

License

NotificationsYou must be signed in to change notification settings

syntax-tree/hast-util-to-jsx-runtime

BuildCoverageDownloadsSize

hast utility to transform a tree topreact, react, solid, svelte, vue, etcetera,with an automatic JSX runtime.

Contents

What is this?

This package is a utility that takes ahast tree and anautomatic JSX runtime and turns the tree into anythingyou wish.

When should I use this?

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.

Install

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>

Use

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}}

API

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.

toJsxRuntime(tree, options)

Transform a hast tree topreact, react, solid, svelte, vue, etcetera,with an automatic JSX runtime.

Parameters
  • tree(Node)— tree to transform
  • options(Options, required)— configuration
Returns

Result from your configured JSX runtime(JSX.Element if defined,otherwiseunknown which you can cast yourself).

Components

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'].

Type
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)

CreateEvaluater

Create an evaluator that turns ESTree ASTs from embedded MDX into values(TypeScript type).

Parameters

There are no parameters.

Returns

Evaluater (Evaluater).

ElementAttributeNameCase

Casing to use for attribute names (TypeScript type).

HTML casing is for exampleclass,stroke-linecap,xml:lang.React casing is for exampleclassName,strokeLinecap,xmlLang.

Type
typeElementAttributeNameCase='html'|'react'

EvaluateExpression

Turn an MDX expression into a value (TypeScript type).

Parameters
  • expression (Expression from@types/estree)— estree expression
Returns

Result of expression (unknown).

EvaluateProgram

Turn an MDX program (export/import statements) into a value (TypeScript type).

Parameters
  • program (Program from@types/estree)— estree program
Returns

Result of program (unknown);should likely beundefined as ESM changes the scope but doesn’t yieldsomething.

Evaluater

Evaluator that turns ESTree ASTs from embedded MDX into values (TypeScripttype).

Fields

ExtraProps

Extra fields we pass (TypeScript type).

Type
typeExtraProps={node?:Element|undefined}

Fragment

Represent the children,typically a symbol (TypeScript type).

Type
typeFragment=unknown

Jsx

Create a production element (TypeScript type).

Parameters
  • type (unknown)— element type:Fragment symbol,tag name (string),component
  • props (Props)— element props,children,and maybenode
  • key (string orundefined)— dynamicly generated key to use
Returns

Element from your framework(JSX.Element if defined,otherwiseunknown which you can cast yourself).

JsxDev

Create a development element (TypeScript type).

Parameters
  • type (unknown)— element type:Fragment symbol,tag name (string),component
  • props (Props)— element props,children,and maybenode
  • key (string orundefined)— dynamicly generated key to use
  • isStaticChildren (boolean)— whether two or more children are passed (in an array),which is whetherjsxs orjsx would be used
  • source (Source)— info about source
  • self (undefined)— nothing (this is used by frameworks that have components,we don’t)
Returns

Element from your framework(JSX.Element if defined,otherwiseunknown which you can cast yourself).

Options

Configuration (TypeScript type).

Fields
  • Fragment (Fragment, required)— fragment
  • jsxDEV (JsxDev, required in development)— development JSX
  • jsxs (Jsx, required in production)— static JSX
  • jsx (Jsx, required in production)— dynamic JSX
  • components (Partial<Components>, optional)— components to use
  • createEvaluater (CreateEvaluater, optional)— create an evaluator that turns ESTree ASTs into values
  • development (boolean, default:false)— whether to usejsxDEV when on orjsx andjsxs when off
  • elementAttributeNameCase(ElementAttributeNameCase,default:'react')— specify casing to use for attribute names
  • filePath (string, optional)— file path to the original source file,passed in source info tojsxDEV when using the automatic runtime withdevelopment: true
  • passNode (boolean, default:false)— pass the hast element node to components
  • space (Space, default:'html')— whethertree is 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 it
  • stylePropertyNameCase(StylePropertyNameCase,default:'dom')— specify casing to use for property names instyle objects
  • tableCellAlignToStyle(boolean, default:true)— turn obsoletealign props ontd andth into CSSstyle props

Props

Properties and children (TypeScript type).

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}

Source

Info about source (TypeScript type).

Fields
  • columnNumber (number orundefined)— column where thing starts (0-indexed)
  • fileName (string orundefined)— name of source file
  • lineNumber (number orundefined)— line where thing starts (1-indexed)

Space

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;usexast if you need to support SVG as XML.

Type
typeSpace='html'|'svg'

StylePropertyNameCase

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.

Type
typeStylePropertyNameCase='css'|'dom'

Errors

The following errors are thrown:

Expected `Fragment` in options

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.

Expected `jsxDEV` in options when `development: true`

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.

Expected `jsx` in production options
Expected `jsxs` in production options

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.

Cannot handle MDX estrees without `createEvaluater`

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.

Cannot parse `style` attribute

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.

Examples

Example: Preact

👉Note:you must setelementAttributeNameCase: '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}}

Example: Solid

👉Note:you must setelementAttributeNameCase: '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}}

Example: Svelte

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.

Example: Vue

👉Note:you must setelementAttributeNameCase: '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}}

Syntax

HTML is parsed according to WHATWG HTML (the living standard),which is also followed by browsers such as Chrome,Firefox,and Safari.

Compatibility

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.

Security

Be careful with user input in your hast tree.Usehast-util-santize to make hast trees safe.

Related

Contribute

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.

License

MIT ©Titus Wormer

About

hast utility to transform to preact, react, solid, svelte, vue, etc

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp