Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ncpa0/jsxte
A JSX based html templating engine for browsers or Node environments.
https://github.com/ncpa0/jsxte
html javascript jsx template-engine
Last synced: 7 days ago
JSON representation
A JSX based html templating engine for browsers or Node environments.
- Host: GitHub
- URL: https://github.com/ncpa0/jsxte
- Owner: ncpa0
- License: mit
- Created: 2022-05-12T23:03:23.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2024-12-16T15:44:03.000Z (27 days ago)
- Last Synced: 2024-12-30T01:16:39.513Z (14 days ago)
- Topics: html, javascript, jsx, template-engine
- Language: TypeScript
- Homepage:
- Size: 3.97 MB
- Stars: 65
- Watchers: 1
- Forks: 3
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# JSX Template Engine
![NPM](https://img.shields.io/npm/l/jsxte?style=for-the-badge) [![npm](https://img.shields.io/npm/v/jsxte?style=for-the-badge)](https://www.npmjs.com/package/jsxte) ![Libraries.io dependency status for latest release](https://img.shields.io/librariesio/release/npm/jsxte?style=for-the-badge) ![GitHub last commit](https://img.shields.io/github/last-commit/ncpa0cpl/jsxte?style=for-the-badge)
A JSX based html templating engine for browsers or Node environments.
1. [Getting started](#getting-started)
1. [Installation](#installation)
2. [Building](#building)
2. [Examples](#examples)
3. [Asynchronous Components](#asynchronous-components)
4. [Context](#context)
1. [Example](#example)
2. [Provider/Consumer Pattern](#providerconsumer-pattern)
5. [Error Boundaries](#error-boundaries)
1. [Example](#example-1)
6. [toHtmlTag symbol](#tohtmltag-symbol)
7. [DomRenderer](#domrenderer)
8. [JsxteRenderer](#jsxterenderer)
9. [Extending the typings](#extending-the-typings)
1. [Adding custom web component tags](#adding-custom-web-component-tags)
2. [Adding a global html attribute](#adding-a-global-html-attribute)
10. [Express JS View Engine](#express-js-view-engine)
11. [Monkey-Patching type definitions](#monkey-patching-type-definitions)
12. [Contributing](#contributing)## Getting started
### Installation
```bash
npm i jsxte
```or
```bash
yarn add jsxte
```### Building
To use the `jsxte` you will have to set up your transpiler to use this package for transforming the JSX syntax, if you use typescript for transpiling all you have to do is set these options in the tsconfig:
```json
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "jsxte"
}
}
```If you use something else, like babel you will also need to adapt the configuration of that, for example: https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#with-a-configuration-file-recommended
(See example configurations [here](./docs/config-examples/)).
Once you are done with that you can start writing your templates and rendering them.
```tsx
import { createElement, renderToHtml } from "jsxte";const Header: JSXTE.Component<{ label: string }> = (props) => {
return{props.label}
;
};const App: JSXTE.Component<{ label: string }> = (props) => {
return (
);
};const html = renderToHtml();
// OR
const html = renderToHtml(createElement(App, { label: "Hello World!" }));
```## Examples
Check out these example repositories:
- [(Express + TypeScript) TODO App](https://github.com/ncpa0/jsxte-with-typescript-example)
- [(Express + Babel) TODO App](https://github.com/ncpa0/jsxte-with-babel-example)## Asynchronous Components
In case you use the templates in a server app in a Node environment you might want to include some data from the database in the html you serve to the client. To make it easier to fetch what's needed and marry it with the templates you can make your components asynchronous and send async requests from within them.
```tsx
import { renderToHtmlAsync } from "jsxte";const Header: JSXTE.Component = () => {
returnHello World
;
};const ToDoList: JSXTE.Component = async () => {
const todos = await fetchMyTodosFromDB();return (
Label
Is Done?
{todos.map((todo) => (
{todo.label}
{todo.isDone ? "yes" : "no"}
))}
);
};const App: JSXTE.Component = () => {
return (
ToDo's:
);
};// If your component contains an asynchronous component at any point, `renderToHtmlAsync` needs to be used instead of `renderToHtml`
const html = await renderToHtmlAsync();
```## Context
Context Map is a interface provided to each functional component that provides a mechanism for providing any arbitrary data to it's descendant. This is primarily to avoid the prop-drilling.
### Example
```tsx
import { defineContext } from "jsxte";const myContext = defineContext<{ label: string }>();
const App: JSXTE.Component = (props, componentApi) => {
// Set the context to a new value, all descendants of this component will have access to it
componentApi.ctx.set(myContext, { label: "Hello" });return ;
};const Foo: JSXTE.Component = (props, componentApi) => {
let label = "";// Check if `myContext` is being provided by any of the ancestors
if (componentApi.ctx.has(myContext)) {
// Retrieve the context data
label = componentApi.ctx.getOrFail(myContext).label;
}return
{label}
;
};
```### Provider/Consumer Pattern
Context also provides a Provider and a Consumer components.
```tsx
const MyContext = defineContext();const App: JSXTE.Component = () => {
return (
{providedValue ?? ""}
}
/>
);
};
```## Error Boundaries
Error boundaries are components that catch errors thrown by their children and allow you to display a fallback UI instead of having the rendering outright fail.
Error boundaries work with both synchronous and asynchronous components. But the `onError` handler should never return an asynchronous component.
### Example
```tsx
import { ErrorBoundary, renderToHtml } from "jsxte";class Boundary extends ErrorBoundary {
render(props: JSXTE.ElementProps, componentApi: ComponentApi) {
return <>{props.children}>;
}onError(
error: unknown,
originalProps: JSXTE.ElementProps,
componentApi: ComponentApi,
) {
returnSomething went wrong!
;
}
}const FailingComponent: JSXTE.Component = () => {
throw new Error("Unexpected failure!");
};const html = renderToHtml(
,
);// html:
//
//Something went wrong!
//
```## toHtmlTag symbol
`Symobl.toHtmlTag` is a special symbol that allows to determine how an object should be stringified when used as a child of a JSX element.
### Example
```tsx
class User {
constructor(
public id: string,
public username: string,
public email: string,
) {}[Symbol.toHtmlTag]() {
return `User: ${this.username}`;
}
}const user = new User("001", "Johny", "[email protected]");
renderToHtml(
{user});
```Result:
```html
User: Johny
```## DomRenderer
`DomRenderer` renders given JSX into a DOM object. It requires a window object to be passed to the constructor.
```tsx
import { DomRenderer } from "jsxte";const renderer = new DomRenderer(window);
const divElement = renderer.render(Hello World!);divElement.outerHTML; //
Hello World!
window.document.body.appendChild(divElement);
```## JsxteRenderer
`JsxteRenderer` is a base class around which HTML and JSON renderer are built upon. This renderer requires a specific interface that provides methods for creating the final output format:
```ts
// T is the type of the renderer return value
export interface ElementGenerator {
createElement(
type: string,
attributes: Array<[attributeName: string, attributeValue: any]>,
children: Array,
): T;
createTextNode(text: string | number | bigint): T;
createFragment(children: Array): T;
}
```It is possible to render to other formats than HTML or JSON by providing a custom `ElementGenerator` implementation to the renderer.
### Example
```tsx
import { JsxteRenderer } from "jsxte";class DomGenerator
implements ElementGenerator
{
createElement(
type: string,
attributes: Array<[attributeName: string, attributeValue: any]>,
children: Array,
): HTMLElement | Text | DocumentFragment {
const element = document.createElement(type);
for (const [name, value] of attributes) {
element.setAttribute(name, value);
}
for (const child of children) {
element.appendChild(child);
}
return element;
}createTextNode(
text: string | number | bigint,
): HTMLElement | Text | DocumentFragment {
return document.createTextNode(String(text));
}createFragment(
children: Array,
): HTMLElement | Text | DocumentFragment {
const fragment = document.createDocumentFragment();
for (const child of children) {
fragment.appendChild(child);
}
return fragment;
}
}const renderer = new JsxteRenderer(new DomGenerator());
const divElement = renderer.render(Hello World!);
```## Extending the typings
JSXTE should be able to parse any html attributes you put in, as well as custom web component tags, although you may see type errors if you use anything that is not defined in the library typings. If you wish to use them it is recommended you extend the typings to disable said errors.
### Adding custom web component tags
To add a typing for a custom web component simply add a declare block in one of your project `.ts` or `.tsx` files, like this one:
```tsx
declare global {
namespace JSX {
interface IntrinsicElements {
"my-custom-web-component": {
/* here include the attributes your component can take */
"data-example-attribute"?: string;
};
}
}
}// with it it's possible to use this without type errors:
const MyComponent: JSXTE.Component = () => (
);
```### Adding a global html attribute
There is a dictionary of html attributes that are available for every default html tag, that dictionary can be extended like so:
```tsx
declare global {
namespace JSXTE {
interface BaseHTMLTagProps {
"new-attribute"?: string;
}
}
}// with it it's possible to use this without type errors:
;
const MyComponent = () =>
```## Express JS View Engine
You can also use `jsxte` with the Express View Engine. To do that, use the `expressExtend` to add the engine support, specify the views directory and then use the express response method `.render()`. The `.render()` method takes the component props as it's second argument.
```ts
import express from "express";
import { expressExtend } from "jsxte";const app = express();
expressExtend(app);app.set("views", path.resolve(__dirname, "views"));
app.get("/", (_, resp) => {
const indexProps = {
/* ... */
};
resp.render("index", indexProps); // will render the `index.js` component located in the ./views file
});
```For this approach to work, the JSX Components must be exported as defaults (ex. `export default () =>
` or `exports.default = () => `) and the views must be transpiled to `.js` files.## Monkey-Patching type definitions
It is possible to monkey-patch type definition of all HTML tags and add new attributes to them.
#### Extend prop types of a specific tag
The following adds a new attribute to the `
` tag - `data-my-attr`:```tsx
declare global {
namespace JSXTE {
interface DivTagProps {
"data-my-attr"?: string;
}
}
}
```#### Extends prop of all html tags
The following adds a new attribute to all html tags - `hx-post`:
```tsx
declare global {
namespace JSXTE {
interface BaseHTMLTagProps {
"hx-post"?: string;
}
}
}
```#### Change the accepted type for a specific attribute
The following adds a `Function` type to the `onclick` attribute of all html tags:
```tsx
declare global {
namespace JSXTE {
interface AttributeAcceptedTypes {
onclick?: Function;
}
}
}
```## Contributing
If you want to contribute please See [CONTRIBUTING.md](./CONTRIBUTING.md)