Docs
Below are the various APIs and capabilities of WCC.
API
renderToString
This function takes a URL "entry point" to a JavaScript file that defines a custom element, and returns the static HTML output of its rendered contents.
const { html } = await renderToString(new URL('./src/index.js', import.meta.url));
import './components/footer.js';
import './components/header.js';
const template = document.createElement('template');
template.innerHTML = `
<style>
:root {
--accent: #367588;
}
</style>
<wcc-header></wcc-header>
<main>
<h1>My Blog Post</h1>
</main>
<wcc-footer></wcc-footer>
`;
export default class Home extends HTMLElement {
connectedCallback() {
if (!this.shadowRoot) {
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
}
}
You can also manually set the innerHTML of a Shadow Root if you don't want to use a template element
import './components/footer.js';
import './components/header.js';
export default class Home extends HTMLElement {
connectedCallback() {
if (!this.shadowRoot) {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:root {
--accent: #367588;
}
</style>
<wcc-header></wcc-header>
<main>
<h1>My Website</h1>
</main>
<wcc-footer></wcc-footer>
`;
}
}
}
Note: WCC will wrap, or not wrap, your entry point's HTML in a custom element tag if you do or do not, respectively, include a
customElements.definein your entry point. WCC will use the tag name you define as the custom element tag name in the generated HTML.You can opt-out of this by passing
falseas the second parameter torenderToString.const { html } = await renderToString(new URL('...'), false);
renderFromHTML
This function takes a string of HTML and an optional array of any top-level custom elements used in the HTML, and returns the static HTML output of the rendered content. WCC will follow and recursively render any imports from those top-level custom elements, however.
const { html } = await renderFromHTML(
`
<html>
<head>
<title>WCC</title>
</head>
<body>
<wcc-header></wcc-header>
<h1>Home Page</h1>
<wcc-footer></wcc-footer>
</body>
</html>
`,
[
new URL('./src/components/footer.js', import.meta.url),
new URL('./src/components/header.js', import.meta.url),
],
);
For example, even if Header or Footer use import to pull in additional custom elements, only the Header and `Footer custom elements used in the "entry" HTML are needed in the array.
Metadata
renderToString and renderFromHTML return not only HTML, but also metadata about all the custom elements registered as part of rendering the entry file.
So for the given HTML:
<wcc-header></wcc-header>
<h1>Hello World</h1>
<wcc-footer></wcc-footer>
and the following conditions:
- index.js does not define a tag of its own, e.g. using
customElements.define(e.g. it is just a "layout" component) <wcc-header>imports<wcc-navigation>
The result would be:
const { metadata } = await renderToString(new URL('./src/index.js', import.meta.url));
console.log({ metadata });
/*
* {
* metadata: {
* 'wcc-footer': { instanceName: 'Footer', moduleURL: [URL], isEntry: true },
* 'wcc-header': { instanceName: 'Header', moduleURL: [URL], isEntry: true },
* 'wcc-navigation': { instanceName: 'Navigation', moduleURL: [URL], isEntry: false }
* }
* }
*/
Progressive Hydration
To achieve an islands architecture-like implementation, if you add the hydration="true" attribute to a custom element, e.g.
<wcc-footer hydration="true"></wcc-footer>
This will be reflected in the returned metadata object from renderToString.
/*
* {
* metadata: {
* 'wcc-footer': { instanceName: 'Footer', moduleURL: [URL], hydrate: 'true' },
* 'wcc-header': { instanceName: 'Header', moduleURL: [URL] },
* 'wcc-navigation': { instanceName: 'Navigation', moduleURL: [URL] }
* }
* }
*
*/
The benefit is that this hint can be used to defer loading of these scripts by using an IntersectionObserver (opens in a new window) (for example), instead of eagerly loading it on page load using a <script> tag.
See this example for more information.
Data
WCC provide a couple mechanisms for data loading.
Constructor Props
Often for frameworks that might have their own needs for data loading and orchestration, a top level "constructor prop" can be provided to renderToString as the final param. The prop will then be passed to the custom element's constructor when loading the module URL.
const request = new Request({
/* ... */
});
const { html } = await renderToString(new URL(moduleUrl), false, request);
This pattern plays really nice with file-based routing and SSR!
export default class PostPage extends HTMLElement {
constructor(request) {
super();
const params = new URLSearchParams(request.url.slice(request.url.indexOf('?')));
this.postId = params.get('id');
}
async connectedCallback() {
const { postId } = this;
const post = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`).then((resp) =>
resp.json(),
);
const { title, body } = post;
this.innerHTML = `
<h2>${title}</h2>
<p>${body}</p>
`;
}
}
Loader
To support component-level data loading and hydration scenarios, a file with a custom element definition can also export a getData function to inject into the custom elements constructor at build time. This can be serialized right into the component's Shadow DOM!
For example, you could preload a counter component with an initial counter state, which would also come through the constructor.
class Counter extends HTMLElement {
constructor(props = {}) {
super();
this.count = props.count;
this.render();
}
// setup your shadow root ...
render() {
this.shadowRoot.innerHTML = `
<script type="application/json">
${JSON.stringify({ count: this.count })}
</script>
<div>
<button id="inc">Increment</button>
<span>Current Count: <span id="count">${this.count}</span></span>
<button id="dec">Decrement</button>
</div>
`;
}
}
export async function getData() {
return {
count: Math.floor(Math.random() * (100 - 0 + 1) + 0),
};
}
Conventions
- Make sure to define your custom elements with
customElements.define - Make sure to include an
export defaultfor your custom element base class - Avoid touching the DOM in
constructormethods (opens in a new window)
TypeScript
TypeScript is supported through "type stripping", which is effectively just removing all the types and leaving only valid JavaScript, before handing off to WCC to do its compiling.
interface User {
name: string;
}
export default class Greeting extends HTMLElement {
connectedCallback() {
const user: User = {
name: this.getAttribute('name') || 'World',
};
this.innerHTML = `
<h3>Hello ${user.name}! 👋</h3>
`;
}
}
customElements.define('wcc-greeting', Greeting);
Prerequisites
There are of couple things you will need to do to use WCC with TypeScript parsing:
- NodeJS version needs to be >=
22.18.0 - You will need to use the .ts extension
- You'll want to enable the
erasableSyntaxOnly(opens in a new window) flag in your tsconfig.json
JSX
⚠️ Very Experimental!
WCC provides the option to author a render function for native HTMLElements that can compile down to a zero run time, web ready custom element! It handles resolving event handling and this references and can manage some basic re-rendering lifecycles.
Example
Below is an example of what is possible right now demonstrated through a Counter component (opens in a new window).
export default class Counter extends HTMLElement {
count: number;
constructor() {
super();
this.count = 0;
}
connectedCallback() {
this.render(); // this is required
}
increment() {
this.count += 1;
this.render();
}
decrement() {
this.count -= 1;
this.render();
}
render() {
const { count } = this;
return (
<div style="color:red;">
<button onclick={(this.count -= 1)}> -</button>
<span>
You have clicked <span class="red">{count}</span> times
</span>
<button onclick={this.increment}> +</button>
<button onclick={this.decrement}> -</button>
</div>
);
}
}
customElements.define('wcc-counter', Counter);
A couple things to observe in the above example:
- The
thisreference is correctly bound to the<wcc-counter>element's state. This works for boththis.countand the event handler,this.increment. - No need for
className!classjust works ™️ - The
styleattribute is just a string, no need to pass an object (e.g.style={{ color: "red" }}) this.countwill know it is a member of the<wcc-counter>'s state, and so will re-runthis.renderautomatically in the compiled output.- Event handlers need to manage their own render function updates.
There is an active discussion tracking features (opens in a new window) and issues in progress (opens in a new window) to continue iterating on this, so please feel free to try it out and give us your feedback!
Private Members and Event Handlers
JSX expressions can access JavaScript private fields and methods, including in text, attributes, and event callbacks:
class Counter extends HTMLElement {
#count = 0;
#increment(event) {
this.#count += 1;
this.render();
}
connectedCallback() {
this.render();
}
render() {
return (
<div>
<p title={this.#count}>Count: {this.#count}</p>
<button onclick={this.#increment}>Increment</button>
</div>
);
}
}
Private event callbacks in direct .map() and .flatMap() loops can use each item's values:
{
items.map((item) => <button onclick={() => this.#select(item.id)}>{item.label}</button>);
}
- Event handlers receive the event, with
thisreferring to the component. Callrender()after changing ordinary state. - Private Signals work with inferred observability to update bound text and attributes automatically.
Prerequisites
There are of couple things you will need to do to use WCC with JSX:
-
NodeJS version needs to be >=
20.10.0 -
You will need to use the .jsx extension
-
Requires the
--importflag when invoking NodeJS$ NODE_OPTIONS="--import wc-compiler/register" node your-script.js
See our example's page for some usages of WCC + JSX. 👀
HTML Interpolation
WCC escapes interpolated strings in ordinary JSX text and attribute values by default and inferred signal effects use DOM setters for subsequent updates. HTML inside those strings is preserved as text, helping prevent HTML injection and related XSS vulnerabilities.
For example, this would display the raw HTML tag:
render() {
const heading = '<template>';
return <h4>{heading}</h4>;
}
<h4><template></h4>
To render HTML or SVG from a string, use WCC’s innerHTML JSX prop. WCC interprets the string as markup without escaping or sanitizing it.
render() {
const heading = '<strong>Hello</strong>';
return <h4 innerHTML={heading}></h4>;
}
<h4><strong>Hello</strong></h4>
Conditionals
Use ternaries and logical expressions to render JSX children, including inside lists:
<section>
{ready ? <p>Ready</p> : null}
{events.length > 0 && (
<ul>
{events.map((event) => (
<li>{event.title}</li>
))}
</ul>
)}
</section>
Only the selected branch is evaluated. null, undefined, and boolean children render nothing, and numbers such as 0 still render. Ordinary text remains escaped, while JSX renders as markup.
Event handlers in conditional JSX can use local variables and private methods:
render() {
const user = this.user;
return (
<section>
{user && (
<button onclick={() => this.#select(user.id)}>Select {user.name}</button>
)}
</section>
);
}
When using inferred observability, put Signal-backed text in its own element beside a conditional:
<section>
{ready ? <p>Ready</p> : null}
<span>{label.get()}</span>
</section>
Placing {label.get()} directly beside the conditional without the wrapping <span> is currently unsupported.
Signal changes do not automatically update conditional content yet. Call
render()to refresh it. Follow #311 (opens in a new window) for reactive conditional support.
Lists
You can render lists in loops using .map().
Reactive loops are not supported yet; changing a Signal containing an array does not automatically update the list.
openComment(event) {
console.log('Opening comment:', event.currentTarget.href);
}
render() {
const replies = [
{ author: 'Alex', text: 'First reply', url: '/comments/1/' },
{ author: 'Sam', text: 'Thanks for sharing!', url: '/comments/2/' },
];
return (
<ul>
{replies.map(({ author, text, url }, index) => (
<li data-index={index}>
<h4>{author}</h4>
<p>{text}</p>
<a href={url} onclick={this.openComment}>Open comment</a>
</li>
))}
</ul>
);
}
- Use nested maps for nested lists, or
.flatMap()to return several elements per item. - JSX can also be assigned to local variables or returned by helper functions.
- Interpolated text and attributes follow the escaping rules described above.
Chain array methods and use block callbacks for additional JavaScript logic:
<ul>
{replies
.filter((reply) => reply.text.length > 0)
.map((reply) => {
const author = reply.author.toUpperCase();
return (
<li>
<strong>{author}</strong>: {reply.text}
</li>
);
})}
</ul>
- Return JSX explicitly from block callbacks.
- Use
.forEach()to collect JSX in an array;.forEach()itself returnsundefined. - Wrap mapped table rows in an explicit
<tbody>.
Arrays can contain both JSX and ordinary values:
const children = [<strong>Rendered as HTML</strong>, '<strong>Displayed as text</strong>', 0, null];
return <div>{children}</div>;
<div><strong>Rendered as HTML</strong><strong>Displayed as text</strong>0</div>
- JSX items render as markup, ordinary strings are escaped as text.
- Nested arrays are rendered in order without separator commas.
null,undefined, and boolean children are omitted;0is preserved.- Arrays can be saved in variables, updated with
.push(), or returned by imported JSX helpers. - Keep JSX values as array items. Concatenating them or calling
.join('')creates an ordinary string, which is escaped when used as a child.
Event handlers in Light DOM
In Light DOM, event handlers in JSX saved to a variable or returned by a helper can target the wrong element when that JSX is inserted inside another element.
This works:
return (
<div>
{replies.map((reply) => (
<a href={reply.url} onclick={this.openComment}>
Open comment
</a>
))}
</div>
);
But this would not work:
const links = replies.map((reply) => (
<a href={reply.url} onclick={this.openComment}>
Open comment
</a>
));
return <div>{links}</div>;
TSX
TSX (.tsx) file are also supported and your HTML will also be type-safe. You'll need to configure JSX in your tsconfig.json by adding these required (and recommend) entries into to your compilerOptions settings:
{
"compilerOptions": {
// required options
"jsx": "preserve",
"jsxImportSource": "wc-compiler",
"lib": ["DOM"],
// additional recommended options
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true
}
}
WCC's JSX aims to follow the HTML and SVG specifications:
- Use standard attribute names such as
class,for, andreadonly, and preserve SVG casing such asviewBox. - TypeScript checks many fixed attribute values, so
loading="lzy"is an error. These checks help catch mistakes but WCC does not validate every HTML or SVG rule at this time. - Define attributes for your own custom elements by adding their tag names and prop types to
JSX.IntrinsicElementsin an app-level.d.tsfile.
If you create your own custom elements and use them in your TSX components, you'll need to define your own interface for them:
declare global {
namespace JSX {
interface IntrinsicElements {
'my-counter': {
count?: number;
};
}
}
}
Declarative Shadow DOM
To opt in to Declarative Shadow DOM with JSX, call attachShadow() in connectedCallback() before calling render(), as shown below. WCC uses this call to identify Shadow DOM components.
During hydration, this.shadowRoot may already contain server-rendered HTML, but that HTML does not initialize ordinary JavaScript fields, like a class member. Read attributes and initialize the state needed by calling render() outside the shadow-root guard.
For example, the Counter component can read its initial count from an attribute:
export default class Counter extends HTMLElement {
connectedCallback() {
this.count = Number(this.getAttribute('count') ?? 0);
if (!this.shadowRoot) {
this.attachShadow({ mode: 'open' });
}
this.render();
}
// ...
}
customElements.define('wcc-counter', Counter);
For Shadow DOM templates with event bindings, the first
render()call reuses populated declarative Shadow DOM to attach listeners; later calls render updated content. Templates without event bindings can replace existing content on the first call. Light DOM components replace their content wheneverrender()runs.
Inferred Observability (Signals)
An optional feature based on TC39 Signals (opens in a new window) that when enabled, will map Signal reads in a component's JSX template to observed attributes (opens in a new window). This feature is inspired by projects such as SolidJS (opens in a new window) and Svelte (opens in a new window).
The JSX transformation will now also do the following:
- Map each Signal to an entry in the
observedAttributesarray - Automatically handle / generate
attributeChangedCallbackupdates - Setup effects (and tear them down in
disconnectedCallback)
So taking the above counter example, enable the inferred observability behavior as an option in the component by exporting it as a const:
// include this line
export const inferredObservability = true;
export default class Counter extends HTMLElement {
constructor() {
super();
// using TC39 signals
this.count = new Signal.State(0);
this.parity = new Signal.Computed(() => (this.count.get() % 2 === 0 ? 'even' : 'odd'));
}
connectedCallback() {
if (!this.shadowRoot) {
this.attachShadow({
mode: 'open',
});
}
// initialize event handlers, reusing existing DSD
this.render();
}
increment() {
this.count.set(this.count.get() + 1);
}
decrement() {
this.count.set(this.count.get() - 1);
}
render() {
const { count, parity } = this;
return (
<div>
<button onclick={this.increment}>Increment (+)</button>
<button onclick={this.decrement}>Decrement (-)</button>
<span>
The count is {count.get()} ({parity.get()})
</span>
</div>
);
}
}
customElements.define('wcc-counter', Counter);
Signals Support
It is required to setup Signal as a global in the browser, and add import maps for the polyfill and WCC's effect function in the <head> of your HTML page(s):
<script type="importmap">
{
"imports": {
"signal-polyfill": "../path/to/node_modules/signal-polyfill/dist/index.js",
"wc-compiler/effect": "../path/to/node_modules/wc-compiler/dist/effect.js"
}
}
</script>
<script type="module">
import { Signal } from 'signal-polyfill';
globalThis.Signal = Signal;
</script>
For TypeScript support, you'll need to expose the Signal type-definition globally:
// alias Signal to avoid name conflicts with the global Signal type
import { Signal as SignalInterface } from "signal-polyfill";
declare global {
const Signal: typeof SignalInterface;
}
Limitations
- Reactivity is only supported at one depth of the JSX tree (opens in a new window)
- Please be aware of the above linked discussion and issue filter which is tracking any known bugs / feature requests / open items related to all things WCC + JSX.
- If you're using Greenwood, the JSX Import plugin (opens in a new window) can automatically handle setting up the
<script>blocks.