PyJSX - Write JSX directly in Python

Posted by zedpowa@reddit | Python | View on Reddit | 61 comments

Working with HTML in Python has always been a bit of a pain. If you want something declarative, there's Jinja, but that is basically a separate language and a lot of Python features are not available. With PyJSX I wanted to add first-class support for HTML in Python.

Here's the repo: https://github.com/tomasr8/pyjsx

What my project does

Put simply, it lets you write JSX in Python. Here's an example:

# coding: jsx
from pyjsx import jsx, JSX
def hello():
    print(<h1>Hello, world!</h1>)

(There's more to it, but this is the gist). Here's a more complex example:

# coding: jsx
from pyjsx import jsx, JSX

def Header(children, style=None, **rest) -> JSX:
    return <h1 style={style}>{children}</h1>

def Main(children, **rest) -> JSX:
    return <main>{children}</main>

def App() -> JSX:
    return (
        <div>
            <Header style={{"color": "red"}}>Hello, world!</Header>
            <Main>
                <p>This was rendered with PyJSX!</p>
            </Main>
        </div>
    )

With the library installed and set up, these examples are directly runnable by the Python interpreter.

Target audience

This tool could be useful for web apps that render HTML, for example as a replacement for Jinja. Compared to Jinja, the advantage it that you don't need to learn an entirely new language - you can use all the tools that Python already has available.

How It Works

The library uses the codec machinery from the stdlib. It registers a new codec called jsx. All Python files which contain JSX must include # coding: jsx. When the interpreter sees that comment, it looks for the corresponding codec which was registered by the library. The library then transpiles the JSX into valid Python which is then run.

Future plans

Ideally getting some IDE support would be nice. At least in VS Code, most features are currently broken which I see as the biggest downside.

Suggestions welcome! Thanks :)