gojsx

package module
v0.6.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2024 License: Apache-2.0 Imports: 37 Imported by: 1

README

gojsx

Render Jsx / Tsx / MD / MDX by Golang.

使用 Go 渲染 Jsx、Tsx、MD、MDX。

Features:

  • Pure Golang, fast and simple

Install

go get github.com/zbysir/gojsx

Example

TSX
import App from "./App";

export default function Index(props) {
  return <html lang="en">
  <head>
    <meta charSet="UTF-8"/>
    <title>Title</title>
    <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>
  </head>
  <body>
  <App {...props}></App>
  </body>
  </html>
}
Mdx
---
title: "Hi"
---

import Footer from "./footer.md"

# {meta.title}

<Footer/>

Render File

Then use gojsx to render .tsx or .mdx file.

package jsx

func TestJsx(t *testing.T) {
	j, err := gojsx.NewJsx(gojsx.Option{})
	if err != nil {
		t.Fatal(err)
	}

	s, err := j.Render("./test/Index.jsx", map[string]interface{}{"li": []int64{1, 2, 3, 4}})
	if err != nil {
		t.Fatal(err)
	}

	t.Logf("%+v", s)
}

Extended syntax

In addition to supporting most of the syntax of jsx, gojsx also supports some special syntax

Render raw html

Use {{__dangerousHTML}} to render raw html without any tag.

export default function Index(props) {
    return <>
      {{__dangerousHTML: props.rawHtml}}
    </>
}

Defects

How to bind event? e.g. onClick

Since the binding event must happen on the browser, and jsx is js code, the browser needs to run the entire jsx component to bind the event correctly, which requires the introduction of react at the front end, otherwise it is very complicated to implement, but the use react will cause jsx to no longer be pure jsx, which in turn will cause gojsx to become more complicated.

So gojsx can't implement event binding that uses simple react syntax.

To save the day, you can either write your own js to manipulate the dom (as everyone did in the JQuery days), or use a library like AlpineJs.

Dependents

Documentation

Index

Constants

This section is empty.

Variables

View Source
var StdFileSystem = stdFileSystem{}

Functions

func AssertFunction

func AssertFunction(v goja.Value) (goja.Callable, bool)

AssertFunction wrap goja.AssertFunction and add prettify error message

func NewMemSourceCache

func NewMemSourceCache() *memSourceCache

func PrettifyException

func PrettifyException(err error) error

PrettifyException make goja exceptions look more prettify.

func TagFieldNameMapper

func TagFieldNameMapper(tagName string, uncapMethods bool, fallbackToUncap bool) goja.FieldNameMapper

func ToKebabCase added in v0.6.2

func ToKebabCase(s string) string

ToKebabCase converts a CamelCase string to a hyphen-separated lowercase string. 用于实现 /node_modules/react-dom/cjs/react-dom-server.node.development.js hyphenateStyleName github.com/gobeam/stringy 和 github.com/stoewer/go-strcase 在处理 “--color“ 都有问题。

func WithCache

func WithCache(cache bool) interface {
	OptionExec
	OptionRender
}

func WithNativeModule

func WithNativeModule(path string, obj map[string]interface{}) interface {
	OptionExec
	OptionRender
}

WithNativeModule 注意,由于有 vm 对象池公用 vm 的情况,所以只能保证同步执行的代码能正确拿到本次运行的值,如果是第一次运行导出 function 再执行的情况,可能拿到的是第二次运行指定的 Module。

Types

type Any

type Any struct {
	Any interface{}
}

type AutoExecJsxProps

type AutoExecJsxProps interface{}

type Callable

type Callable func(args ...interface{}) (v goja.Value, err error)

type EsBuildTransform

type EsBuildTransform struct {
	// contains filtered or unexported fields
}

func (*EsBuildTransform) Transform

func (e *EsBuildTransform) Transform(filePath string, code []byte, format TransformerFormat) (out []byte, err error)

type EsBuildTransformOptions

type EsBuildTransformOptions struct {
	Minify          bool
	MarkdownOptions []goldmark.Option
}

type Exception

type Exception struct {
	Text   string
	Stacks []string
}

func (*Exception) Error

func (e *Exception) Error() string

type ExportDefault

type ExportDefault interface {
	// contains filtered or unexported methods
}

type Jsx

type Jsx struct {
	// contains filtered or unexported fields
}

func NewJsx

func NewJsx(op Option) (*Jsx, error)

func (*Jsx) Exec

func (j *Jsx) Exec(file string, opts ...OptionExec) (ex *ModuleExport, err error)

func (*Jsx) ExecCode

func (j *Jsx) ExecCode(src []byte, opts ...OptionExec) (ex *ModuleExport, err error)

ExecCode code 需要是 ESModule 格式,如 export default () => <></>

func (*Jsx) RegisterModule

func (j *Jsx) RegisterModule(name string, obj map[string]interface{})

func (*Jsx) Render

func (j *Jsx) Render(file string, props interface{}, opts ...OptionRender) (n string, err error)

Render a component to html

func (*Jsx) RenderCode

func (j *Jsx) RenderCode(code []byte, props interface{}, opts ...OptionExec) (n string, ctx *RenderCtx, err error)

RenderCode code to html

func (*Jsx) RenderCtx

func (j *Jsx) RenderCtx(file string, props interface{}, opts ...OptionRender) (n string, ctx *RenderCtx, err error)

RenderCtx a component to html

type ModuleExport

type ModuleExport struct {
	// One of VDom, Callable, Any
	// VDom if WithAutoExecJsx
	// Callable if export a function
	Default ExportDefault
	Exports map[string]interface{}
}

type Option

type Option struct {
	SourceCache SourceCache
	Debug       bool // enable to get more log
	// 最多的 vm 对象数量,指定为 1 表示只会同时有一个 vm 运行,默认为 2000
	VmMaxTotal  int
	Transformer Transformer
	// Fs 没办法做到每次执行代码时指定,因为 require 可能会发生在异步 function 里,fs 改变会导致加载文件错误
	Fs fs.FS // default is StdFileSystem

	// GojaFieldNameMapper Specify the mapping of field names in go struct and js.
	// via: https://github.com/dop251/goja#mapping-struct-field-and-method-names
	GojaFieldNameMapper goja.FieldNameMapper
}

type OptionExec

type OptionExec interface {
	// contains filtered or unexported methods
}

func WithAutoExecJsx

func WithAutoExecJsx(t AutoExecJsxProps) OptionExec

func WithFileName

func WithFileName(fn string) OptionExec

func WithGlobalVar

func WithGlobalVar(k string, v interface{}) OptionExec

WithGlobalVar 注意,由于有 vm 对象池公用 vm 的情况,所以只能保证同步执行的代码能正确拿到本次运行的值,如果是第一次运行导出 function 再执行的情况,可能拿到的是第二次运行指定的 GlobalVar。

type OptionRender

type OptionRender interface {
	// contains filtered or unexported methods
}

type RenderCtx

type RenderCtx struct {
	// Hydrate 用于将组件的数据提取到单独的文件中。
	Hydrate map[string]map[string]string // id => [event type => event code]
}

func Render

func Render(i interface{}) (string, *RenderCtx)

func (*RenderCtx) AddHydrate

func (ctx *RenderCtx) AddHydrate(id string, props map[string]string)

AddHydrate add hydrate

type RunJsOption

type RunJsOption func(*execOptions)

type Source

type Source struct {
	SrcMd5    string
	Body      []byte
	CreatedAt string
}

type SourceCache

type SourceCache interface {
	Get(key string) (f []byte, exist bool, err error)
	Set(key string, f []byte) (err error)
}

type Transformer

type Transformer interface {
	Transform(filePath string, src []byte, format TransformerFormat) (out []byte, err error)
}

type TransformerFormat

type TransformerFormat uint8
const (
	TransformerNone           TransformerFormat = 0
	TransformerFormatDefault  TransformerFormat = 1
	TransformerFormatIIFE     TransformerFormat = 2
	TransformerFormatCommonJS TransformerFormat = 3
	TransformerFormatESModule TransformerFormat = 4
)

type VDom

type VDom map[string]interface{}

func (VDom) Render

func (v VDom) Render() (string, *RenderCtx)

func (VDom) String

func (v VDom) String() string

type VDomOrInterface

type VDomOrInterface struct {
	// VDom     VDom
	Callable goja.Callable

	Any interface{}
}

Directories

Path Synopsis
internal
js
pkg
htmlparser
Package html is an HTML5 lexer following the specifications at http://www.w3.org/TR/html5/syntax.html.
Package html is an HTML5 lexer following the specifications at http://www.w3.org/TR/html5/syntax.html.
mdx
test

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL