A simple jsx to DOM Node
parser.
To create a DOM element in JavaScript, we could use document.createElement
:
const div = document.createElement('div');
div.classList.add('example');
div.innerText = 'hello there';
div.addEventListener('click', () => console.log('clicked!'));
Texsaur lets you do this with jsx instead:
import jsx from 'texsaur';
const div = (
<div class="example"
onclick={() => console.log('clicked!')}>
Hello there
</div>
) as HTMLElement;
You can create a reusable component by creating a function:
function Header({ title }: { title: string }) {
return <header>
<h1>{title}</h1>
</header>
}
document.body.appendChild(
<div>
<Header title="Hello there" />
{/* Same as */}
{Header({ title: 'Hello there.' })}
</div>
)
To work with JSX, the function must implement Component
:
interface Component {
(properties?: { [key: string]: any }, children?: Node | Node[]): Element
}
JSX requires a compiler/bundler. Here are a few example set-ups (note: checkout the examples/ directory for corresponding sample projects):
In vite.config.js
, add the esbuild.jsx
property:
export default {
esbuild: {
jsxFactory: 'jsx',
jsxFragment: 'jsx.Fragment', // optional - enables fragments (<></>)
}
}
Examples:
First, configure your tsconfig.json
:
"compilerOptions": {
"jsx": "react", // "preserve" may also serve your needs.
"jsxFactory": "jsx",
"jsxFragmentFactory": "jsx.Fragment" // optional - enables fragments (<></>)
}
Then, import Texsaur in any .tsx file:
import jsx from 'texsaur';
const div = <div>Hello there.</div>;