WIP: A basic JSX factory for use in projects leveraging web components
- Drop-in ready
- TypeScript support
- Compiler that can convert JSX to JSX factory JavaScript calls
yarn add jsx-for-web-components
We'll use TypeScript and Rollup to build for the browser. Let's start with pulling in some dependencies:
yarn add --dev typescript rollup rollup-plugin-node-resolve rollup-plugin-typescript2
A couple configuration files to help the project build correctly:
./tsconfig.json
{
"compilerOptions": {
"jsx": "react",
"jsxFactory": "h",
"moduleResolution": "node",
"target": "es2015"
}
}
./rollup.config.js
import resolve from "rollup-plugin-node-resolve";
import typescript from "rollup-plugin-typescript2";
export default {
input: "./src/index.tsx",
output: {
file: "./dist/index.js",
format: "iife",
},
plugins: [
resolve({
extensions: [ '.js', '.ts', '.tsx' ],
}),
typescript({
typescript: require("typescript"),
}),
],
};
Define your custom element:
./src/index.tsx
import { h, JSXCustomElement } from "jsx-for-web-components";
class ExampleElement extends JSXCustomElement {
static elementName = "example-element";
public render() {
return <div id="testing">hello</div>;
}
}
ExampleElement.register();
Leverage your custom element:
./index.html
<!DOCTYPE html>
<script src="/dist/index.js" defer></script>
<example-element></example-element>
After building the project with rollup -c rollup.config.js
, you should be able to load your HTML in a browser to see your work.
While there is some setup performed within the constructor
of JSXCustomElement
, the DOM nodes defined by your render
method are not attached until the connectedCallback
method is called. If you need to leverage this callback within your code, be sure to call the super method, e.g.:
class ExampleElement extends JSXCustomElement {
// ...
public connectedCallback() {
super.connectedCallback();
// your code
}
}
This project is licensed under the MIT License. See LICENSE for details.