DEV Community

Cover image for What's New in Stencil 5
John Jenkins
John Jenkins

Posted on

What's New in Stencil 5

Stencil 5 RC is here - let's have a look at what's new

If you haven't used Stencil before, start with the next section. If you have, skip to what's new.

Quick recap - what is Stencil?

Stencil (JS) is a 10-year-old project; a "web-component-compiler" where TypeScript / JSX goes in ...

// src/my-greeting.tsx

import { Component, Prop } from '@stencil/core';

@Component({ tag: 'my-greeting' })
export class MyGreeting {
  @Prop() name = 'World';

  render() {
    return <p>Hello, {this.name}!</p>;
  }
}
Enter fullscreen mode Exit fullscreen mode

... and standard custom elements (<my-greeting name="Stencil">) come out. The important part in that process is the extraction of meta-data which can be used for lots of stuff:

  • Different kinds of bundles, like one optimised for lazy-loading, one for cherry picking and one for SSR
  • Lots of docs outputs for IDEs, agents and JSON manifests
  • Framework wrappers which smooth the end-developer experience, making the components feel 'native' in things like NextJS or Angular

With its build-first, batteries-included toolchain approach, Stencil is a good fit for building component libraries and design systems (and v5 has been tuned with that in mind).

Where's Stencil been?

3 1/2 years since its last major release, Stencil has felt a bit unloved. In that time, devs have come and gone, ownership and governance have changed, but it's gone from being open-code to becoming open-source proper, readily accepting PRs and ideas from the wider community.

That's where I came in. Having been a long-term fan of custom elements and of Stencil's USP (meta in, whatever you want out), I've been quietly contributing to and guiding the project for the last 1-2 years.

Try It

Start a new project:

npm init stencil@next
Enter fullscreen mode Exit fullscreen mode

Or upgrade an existing one - see Upgrading. The v5 docs cover everything below in more depth.

What's coming in Stencil 5?

A new CLI, a new bundler, CSS-only components, signals, reactive controllers, server rendering for any framework and language, new DX for global styling, less boilerplate and better testing solutions through Vitest and Playwright. The updated v5 docs are ready and waiting with new in-browser playgrounds.

Contents

A New CLI

stencil init scaffolds a project by asking what you need: output targets, a framework integration (like for React, Vue or Angular), a test runner, a CSS preprocessor. It installs and configures what you pick.

The stencil init wizard

To add something later, run stencil add. It shows the same choices as init, and works with any participating package that ships its own setup wizard. So stencil add @stencil/vitest installs Vitest, guides you through a wizard and writes its config.

stencil migrate updates a v4 project. More on that below.

Four Kinds of Component

I feel like design systems need more than one kind of component. A badge might only need styles. A share link might be best as a slotted <a> that gets extra behaviour once JavaScript loads. A dropdown renders its own markup. A complex input might want shadow DOM, to keep its internals separate from the page.

Component Archetypes compares the four kinds of component you can build: CSS-only, progressively enhanced, custom elements without shadow DOM, and custom elements with it.

For any component requiring JavaScript, Stencil v5 has moved these options into a new encapsulation object:

// src/my-input.tsx

@Component({
  tag: 'my-input',
  encapsulation: { type: 'shadow' }, // or 'scoped', or 'none'
})
Enter fullscreen mode Exit fullscreen mode

Left out, the component renders into the light DOM with no encapsulation (and components without shadow DOM still get <slot>s). scoped and none components can also pick / override which light DOM patches they need, per component.

v5 also introduces new globalStyle / globalStyleUrl properties on your component definition:

@Component({
  tag: 'my-input',
  style: `:host { display: block; }`,
  // ^ style your component internals after it's loaded
  globalStyle: `my-input { min-height: 20px; }`
  // ^ pre-style your component or its contents before it's loaded
  // to help with FOUC, CLS and progressive enhancement
})
Enter fullscreen mode Exit fullscreen mode

Read more about co-locating styles with your components.

CSS-Only Components

When components don't need JavaScript at all (a badge, a divider, a layout grid), you can write one as a stylesheet. A /** @component */ comment turns a rule into a component:

/* src/my-badge.css */
/**
 * @component
 * A small label for a status or count.
 */
my-badge {
  /** The badge's background color. */
  --badge-color: #e0e0e0;
  display: inline-flex;
  background: var(--badge-color);

  /** Variant (the enum type attribute is auto-documented) */
  &[variant='success'] {
    --badge-color: #c8f0d0;
  }
  &[variant='danger'] {
    --badge-color: #f8d0d0;
  }

  /** Pill (the boolean type attribute is auto-documented) */
  &[pill] {
    border-radius: 999px;
  }

  /** Icon (slots are auto-documented) */
  > [slot='icon'] {
    width: 1em;
  }
}
Enter fullscreen mode Exit fullscreen mode

<my-badge> is never registered as a custom element; there's no JS runtime to load. Stencil still adds it to your JSX types and generated docs, and ships its CSS with your global styles.

Thanks to Burton Smith's initial idea, I wholly agreed and went all-in!

New Shadow DOM Features

For components that do use shadow DOM, more of the platform's shadow root options are now supported.

Scoped custom element registries let two versions of a library define the same tag on one page, each in its own part of it. They now have first-class support - see Scoped Registries.

  • referenceTarget forwards a <label for> or aria-labelledby that points at your component to an element inside its shadow root (so far only Chromium-based browsers support this - Chrome and Edge 152+).
  • mode: 'closed' disables access to element.shadowRoot.
  • clonable keeps the shadow root when the host is deep-cloned with cloneNode(true) (otherwise you get an empty shell).
  • serializable includes the shadow root when the host is serialized with getHTML({ serializableShadowRoots: true }).
  • delegatesFocus and slotAssignment sit alongside them in the same object.
@Component({
  tag: 'my-input',
  encapsulation: {
    type: 'shadow',
    referenceTarget: 'field',
    mode: 'closed',
    clonable: true,
  },
})
export class MyInput {
  render() {
    return <input id="field" />;
  }
}
Enter fullscreen mode Exit fullscreen mode

Form-associated components no longer need a flag - using the @AttachInternals() decorator sets that up for you.

Signals

Stencil v5 includes Preact Signals. A signal holds a value outside any one component, so several components can share it. Put a signal in JSX and Stencil updates that one text node when it changes, without rendering the component again:

// src/count.ts

import { signal } from '@stencil/core/signals';

export const count = signal(0);
Enter fullscreen mode Exit fullscreen mode
// src/my-counter.tsx

import { Component } from '@stencil/core';
import { count } from './count';

@Component({ tag: 'my-counter' })
export class MyCounter {
  render() {
    return <button onClick={() => count.value++}>{count}</button>;
  }
}
Enter fullscreen mode Exit fullscreen mode

A new @Effect() decorator (also from @stencil/core/signals) runs a method again whenever a signal it reads changes.

Signal-Backed Components

Turn on signalBacking in your config and every @Prop() and @State() is stored in a signal too (you don't have to change your component code). This makes your components' props subscribable from outside. Other components and Preact Signals code can react to them directly, and frameworks can follow along without listening for events or watching attributes:

// my-app/src/doubled-volume.ts

import { getSignal, computed } from '@stencil/core/signals';

// <my-slider> has a `@Prop() value: number`
const sliderEl = document.querySelector('my-slider');
await sliderEl.componentOnReady();

const volume = getSignal<number>(sliderEl, 'value');
export const doubledVolume = computed(() => volume.value * 2);
Enter fullscreen mode Exit fullscreen mode

The Signals guide has live examples.

Reactive Controllers

Stencil v5 now has much better interop with reactive controllers - reusable objects that hook into a component's lifecycle - without writing glue code. Mix ReactiveControllerHost into a component, and every controller you add gets hostConnected, hostWillRender, hostDidUpdate etc:

// src/mouse-controller.ts

import type { ReactiveController, ReactiveControllerHostInterface } from '@stencil/core';

export class MouseController implements ReactiveController {
  pos = { x: 0, y: 0 };

  constructor(private host: ReactiveControllerHostInterface) {
    host.addController(this);
  }

  private onMove = (e: MouseEvent) => {
    this.pos = { x: e.clientX, y: e.clientY };
    this.host.requestUpdate();
  };

  hostConnected() {
    window.addEventListener('mousemove', this.onMove);
  }

  hostDisconnected() {
    window.removeEventListener('mousemove', this.onMove);
  }
}
Enter fullscreen mode Exit fullscreen mode
// src/my-mouse.tsx

import { Component, Host, Mixin, ReactiveControllerHost } from '@stencil/core';
import { MouseController } from './mouse-controller';

@Component({ tag: 'my-mouse' })
export class MyMouse extends Mixin(ReactiveControllerHost) {
  private mouse = new MouseController(this);

  render() {
    return <Host>{this.mouse.pos.x}, {this.mouse.pos.y}</Host>;
  }
}
Enter fullscreen mode Exit fullscreen mode

See some more examples.

Styling

Global styles now get their own output target, global-style. You can have as many as you like (e.g. a separate light and dark theme) and choose, with inject, whether each one is also added to your shadow DOM components. Read more.

Add @import "stencil-hydrate"; to a global stylesheet and Stencil writes its FOUC-prevention CSS (hiding components until they've loaded) into that file at build time. This replaces the default behaviour of the loader injecting a <style> tag at runtime.

Less Boilerplate

v5 has removed a lot of the requirements around boilerplate, so a new, default project doesn't need:

  • A stencil.config.ts. With no config, Stencil builds a loader-bundle - the output most design systems want.
  • A namespace. It's taken from your package.json name (or the directory name).
  • A tsconfig.json. If there isn't one, Stencil writes one for you.
  • An index.html. The dev server generates preview pages for your components.
  • Global style / script wiring. src/global.{css,scss,sass} and src/global.{ts,js} are picked up automatically.

A folder of .tsx files and npx stencil build --dev --serve is enough to get going. Add config later if you need it.

Development Previews

We've added auto-previews to Stencil's built-in dev server.

Add examples to the usage folder (e.g. src/my-button/usage/basic.md), and their html code blocks become the preview. Run stencil build --dev --serve and navigate to the component's folder:

My button component preview

If you prefer granular control, continue using index.html files as you do now. Alternatively, we've made the integration with Storybook even nicer :)

Server-Side Rendering

The dist-hydrate-script output target is now ssr. The SSR examples repo has working setups for Next.js, React Router, TanStack Start, Nuxt, SvelteKit, SolidStart, Astro, Angular and Eleventy.

Streaming

SSR can now stream - streamToString() returns a web-standard ReadableStream, so it runs in Node, Cloudflare Workers, Deno, Bun and other edge runtimes.

SSR WASM

There's also the new (still a bit experimental) ssr-wasm output target. It compiles your server renderer to WebAssembly, so a server in PHP, Java, Go, .NET or any other language can render your components without Node.js. Check out the SSR WASM examples repo.

Using Your Components Elsewhere

We've added more outputs and supporting libraries, meaning your components can compile, run and be read in more ways.

  • Framework types. React 19, Vue, Solid, Svelte, Preact and Astro render custom elements without wrappers. @stencil/types-output-target generates the types that let them type-check your components' props and events.
  • The bundler plugin. @stencil/unplugin compiles Stencil components inside Vite, webpack, Rspack, Rollup or esbuild. Write components directly in an app, with no separate Stencil build. So far we mainly use it for Vitest and Storybook, but it may be useful elsewhere.
  • An agent skill. The docs-agent-skill output target generates a skill from your JSDoc comments and usage examples, so AI coding agents can use your library correctly.

Testing

Stencil's built-in test runner (stencil test --spec and --e2e, with Jest and Puppeteer) is gone. Its replacements are separate packages:

Both have migration guides, and you can keep your existing newSpecPage() tests while you move.

Under the Hood

Builds are around 1.5–2× faster than v4 (benchmarks).

  • Rolldown. Stencil now bundles with Rolldown in place of Rollup. rollupConfig and rollupPlugins become rolldownConfig and rolldownPlugins.
  • LightningCSS. Lightning CSS now autoprefixes and minifies your CSS, in place of Autoprefixer and Stencil's own minifier.
  • OXC. JavaScript is minified with OXC by default. Set jsMinifier: 'terser' to keep using Terser.
  • Your TypeScript. Stencil uses the TypeScript in your project (5.x or 6.x), and no longer ships its own copy.
  • ESM. Stencil's own packages are pure ESM, and the loader-bundle and ssr outputs no longer generate CommonJS by default.
  • Renamed output targets. dist is now loader-bundle, dist-custom-elements is standalone, and dist-hydrate-script is ssr.

Upgrading

Upgrade from the latest Stencil v4:

npm install @stencil/core@rc --save-dev
npx stencil migrate
Enter fullscreen mode Exit fullscreen mode

stencil migrate --dry-run shows what it will change first. Most of the config and decorator changes are automatic, but a few things to look out for:

  • Node.js 22 or later is required.
  • Browser support is now ES2022: Chrome and Edge 94+, Firefox 93+ and Safari 16.4+.
  • Boolean props follow the HTML spec. <my-cmp disabled="false"> now means disabled === true - remove the attribute instead.
  • TypeScript 6 (installed if your project doesn't pin 5.x) rejects "moduleResolution": "node" and turns strict on.
  • ESM only. require('@stencil/core/...') no longer works.

The upgrade guide goes through each step, and the full list of breaking changes explains the reason for every change.

What's Next

Try out Stencil v5 today - and let us know your thoughts or woes.

If something is broken, or behaves differently from v4 (and isn't described in breaking changes), please open an issue or come find me in Discord.

Top comments (0)