Develop a custom elements library with SSR-friendly hydration, theming, and TypeScript…
- User
Develop a custom elements library with SSR-friendly hydration, theming, and TypeScript tooling.
Assistant
Develop a custom elements library with SSR-friendly hydration, theming, and TypeScript tooling.
The user wants a complete example of a custom elements (Web Components) library that includes:
This is a sophisticated request that requires a well-structured project. I will design a solution that avoids complex build configurations (like Webpack) to keep it focused on the core concepts, while still demonstrating best practices.
Key Components:
MyCard component.customElements.define requires window or document.
<template shadowrootmode="open">.tsconfig.json and maybe a simple build script (using tsc directly).Step-by-Step Plan:
src, dist, etc.tsc to output standard JS and .d.ts files.MyCard.ts):
attachShadow, etc.).server.ts or just a utility): Show how to generate the HTML string containing Declarative Shadow DOM. Since this is a library example, I'll provide a function that generates the HTML string, simulating what a server would do.hydrate.ts): A script that runs on the client to upgrade the static HTML into interactive components.index.html showing how it all comes together.Refining the Hydration Strategy:
customElements.define works, but if the component relies on complex state restoration or if the browser doesn't support Declarative Shadow DOM (DSD), we need a polyfill or a specific strategy.<my-card><template shadowrootmode="open">...</template></my-card>.customElements.define('my-card', MyCard).this.shadowRoot already exists.Refining Theming:
:host.style="--my-card-bg: red;".Refining TypeScript Tooling:
tsc for the build.package.json setup for exports.Let's write the code.
Self-Correction during thought process: Should I use Lit?
Detailed Implementation Steps:
MyComponent.ts:
<style> tags (for simplicity in vanilla JS, <style> inside the template is easier for SSR stringification, but Constructable Stylesheets are better for performance. I'll stick to <style> inside the shadow root for maximum compatibility and ease of SSR string generation).if (!this.shadowRoot) this.attachShadow({ mode: 'open' });renderToString.ts (SSR helper):
<template shadowrootmode="open">.hydrate.ts:
tsconfig.json: Standard strict settings.
Let's construct the response.
This covers all requirements. I will make sure the hydration logic explicitly handles the existing shadow root to demonstrate "SSR-friendly" behavior (i.e., not destroying server-rendered DOM).
One specific detail: Declarative Shadow DOM (DSD) is supported in Chrome, but Safari/Firefox support is recent or pending.
Let's draft the MyCard component.
const template = document.createElement('template');
template.innerHTML = `
<style>
:host {
display: block;
/* Theme variables */
--bg-color: #fff;
--text-color: #333;
background: var(--bg-color);
color: var(--text-color);
border: 1px solid #ccc;
padding: 16px;
}
</style>
<div class="card-content">
<slot name="header"></slot>
<slot></slot>
</div>
`;
class MyCard extends HTMLElement {
// ... implementation
}
For SSR, instead of document.createElement, we just return a string.
For Hydration, the browser sees the HTML string. If DSD is supported, the shadow DOM is already parsed. The JS class needs to detect this.shadowRoot.
constructor() {
super();
// Only attach if not already attached by the parser (SSR/Hydration)
if (!this.shadowRoot) {
this.attachShadow({ mode: 'open' }).appendChild(template.content.cloneNode(true));
}
// If shadowRoot exists, we assume it contains the SSR content.
// We might need to hydrate event listeners here.
}
This looks solid. I will present this as a cohesive library structure.
Structure of the Output:
package.json, tsconfig.json.I will ensure the code is strictly typed.
(Self-Correction): The user asked for a "custom elements library". I should organize the code so it looks like an exportable module, not just a script file.
Final check on "SSR-friendly". The most robust way to do SSR for Web Components right now is Declarative Shadow DOM. The specific "Hydration" step in Vanilla JS usually means:
customElements.upgrade or define happens.this.shadowRoot exists. It stops.Let's go. This guide outlines a production-grade architecture for a Custom Elements (Web Components) library. It focuses on three core requirements: SSR compatibility via Declarative Shadow DOM (DSD), Theming via CSS Properties, and Type Safety via TypeScript.
We will use a "Vanilla" TypeScript approach to avoid framework lock-in, ensuring the components work everywhere.
Directory Structure:
/my-ui-library
├── src/
│ ├── components/
│ │ └── my-card.ts # Specific component logic
│ ├── themes/
│ │ └── default.css # CSS Variables
│ ├── utils/
│ │ └── ssr.ts # Server-side rendering helpers
│ └── index.ts # Main entry point
├── package.json
└── tsconfig.json
package.json (Key Configs)
{
"name": "my-ui-library",
"type": "module",
"types": "dist/index.d.ts",
"exports": {
".": "./dist/index.js",
"./themes/default.css": "./dist/themes/default.css"
},
"scripts": {
"build": "tsc",
"serve": "node server.mjs"
},
"devDependencies": {
"typescript": "^5.0.0"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"declaration": true,
"outDir": "./dist",
"strict": true,
"experimentalDecorators": false,
"useDefineForClassFields": false
},
"include": ["src"]
}
We define design tokens in a standard CSS file. This allows users to override variables without recompiling your TypeScript.
src/themes/default.css
:host {
--ui-bg: #ffffff;
--ui-text: #1a1a1a;
--ui-primary: #007bff;
--ui-radius: 8px;
--ui-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
This is the core logic. To make it SSR-friendly, we use Declarative Shadow DOM.
The component performs a "Hydration Check":
<template shadowrootmode="open"> inside the element.shadowRoot. The component skips the template cloning and only attaches event listeners.src/components/my-card.ts
// Define the HTML template string separately for re-use in SSR utils
const templateHTML = `
<style>
:host {
display: block;
background: var(--ui-bg, white);
color: var(--ui-text, black);
border-radius: var(--ui-radius, 4px);
box-shadow: var(--ui-shadow, none);
padding: 1.5rem;
font-family: system-ui, sans-serif;
}
::slotted(h2) {
margin-top: 0;
color: var(--ui-primary);
}
</style>
<slot name="header"></slot>
<div class="body">
<slot></slot>
</div>
<button id="action-btn">Action</button>
`;
const template = document.createElement('template');
template.innerHTML = templateHTML;
export class MyCard extends HTMLElement {
static get observedAttributes() {
return ['disabled'];
}
constructor() {
super();
// SSR HYDRATION LOGIC:
// If the element already has a shadowRoot (populated by Declarative Shadow DOM),
// we do NOT clone the node again. We just proceed to attach listeners.
if (!this.shadowRoot) {
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
}
connectedCallback() {
this.upgradeProperty('disabled');
this.attachEventListeners();
this.render(); // Initial render logic if needed
}
// Helper to handle properties that might have been set before the element was upgraded
private upgradeProperty(prop: string) {
if (this.hasOwnProperty(prop)) {
const value = (this as any)[prop];
delete (this as any)[prop];
(this as any)[prop] = value;
}
}
private attachEventListeners() {
const btn = this.shadowRoot?.querySelector('#action-btn');
// Ensure we don't duplicate listeners in case of reconnection
btn?.addEventListener('click', this.handleAction);
}
private handleAction = (e: Event) => {
if (this.disabled) return;
this.dispatchEvent(new CustomEvent('card-action', {
detail: { timestamp: Date.now() },
bubbles: true,
composed: true
}));
}
attributeChangedCallback(name: string, oldVal: string | null, newVal: string | null) {
if (name === 'disabled') {
const btn = this.shadowRoot?.querySelector('#action-btn');
if (btn) {
(btn as HTMLButtonElement).disabled = newVal !== null;
}
}
}
// TypeScript Property API
get disabled(): boolean {
return this.hasAttribute('disabled');
}
set disabled(val: boolean) {
if (val) {
this.setAttribute('disabled', '');
} else {
this.removeAttribute('disabled');
}
}
render() {
// Logic to update UI based on state (if complex, can use a simple virtual DOM diff or just string updates)
}
}
// Auto-register ONLY if not already defined (SSR safety)
if (!customElements.get('my-card')) {
customElements.define('my-card', MyCard);
}
When rendering on the server (Node.js), standard Web Components fail because document doesn't exist. However, we just want to generate an HTML string.
src/utils/ssr.ts
import { templateHTML } from '../components/my-card'; // Assuming you export the string
// Helper to construct Declarative Shadow DOM HTML string
export function renderDeclarativeShadowDOM(tagName: string, attributes: Record<string, string>, lightDomContent: string): string {
const attrString = Object.entries(attributes)
.map(([key, val]) => `${key}="${val}"`)
.join(' ');
// Declarative Shadow DOM structure
// 1. Element opens
// 2. Template with shadowrootmode="open"
// 3. Light DOM content
// 4. Element closes
return `
<${tagName} ${attrString}>
<template shadowrootmode="open">
${templateHTML}
</template>
${lightDomContent}
</${tagName}>
`;
}
Note: For a real production app, you would use a stream-based HTML parser like parse5 or htmlparser2 to inject the template automatically, rather than manual string interpolation.
Here is how a backend (like Node.js or Deno) would render the page, and how the browser would hydrate it.
Server Side (server.mjs - Pseudo code)
import { renderDeclarativeShadowDOM } from './dist/utils/ssr.js';
// 1. Generate the HTML string with DSD
const cardHtml = renderDeclarativeShadowDOM(
'my-card',
{ class: 'featured' },
'<h2 slot="header">Hello SSR</h2><p>This content renders before JS loads.</p>'
);
// 2. Send to client
const html = `
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./dist/themes/default.css">
</head>
<body>
<!-- Styles load immediately, content is visible immediately -->
${cardHtml}
<script type="module" src="./dist/index.js"></script>
</body>
</html>
`;
Client Side (Browser)
<template shadowrootmode="open"> and constructs the Shadow DOM immediately. The user sees the styled card before JavaScript downloads.dist/index.js loads. It defines customElements.define('my-card', MyCard).MyCard class.constructor runs. It checks if (!this.shadowRoot). Since the Shadow Root already exists from DSD, it skips template cloning. It runs connectedCallback, attaching the click event listeners. The component is now interactive.--ui-bg), developers consuming your library can wrap your component in a div with a different class (e.g., .dark-mode) and override the variables, changing the look without touching the component internals.tsconfig generates .d.ts files, enabling Intellisense in VS Code/WebStorm for properties like card.disabled.<template shadowrootmode="open">, we eliminate the "Flash of Unstyled Content" (FOUC) common in Web Components, making them performant and SEO-friendly.