Creating components with Stencil

Stencil is a compiler for web components. It allows developers to create custom elements for their website while also allowing the use of common developer tools such as JSX and TypeScript.

Stencil provides a great command-line tool to get started. Build out a project by running npm init stencil on the command line and following the on-screen prompts to create a custom element.

This stamps out a development environment and an example element that we can update as needed.

import { Component, Prop, h } from '@stencil/core'; import { format } from '../../utils/utils'; @Component({ tag: 'my-component', styleUrl: 'my-component.css', shadow: true }) export class MyComponent { /** * The first name */ @Prop() first: string; /** * The middle name */ @Prop() middle: string; /** * The last name */ @Prop() last: string; private getText(): string { return format(this.first, this.middle, this.last); } render() { return
Hello, World! I'm {this.getText()}
; } }

The @Component decorator denotes this class as a component. It requires a tag name (in this case my-component) but can take many more configuration options.

Each prop is denoted by the @Prop decorator. These are values that can be changed externally through the component's attributes.

The render() method describes what the component should display. This is written in JSX and can contain anything required - HTML, JS or even other Stencil components.

Each component can have some styles associated with it. These are applied to the component based on the path suppplied to the styleUrl property in the component set up.

:root { font-size: 18px; font-weight: bold; text-align: center; }

The styles applied here are scoped only to that component. This means they can be as generic as possible without having to worry about the contents spilling out and affecting the rest of the page.

The result is a component that can be used like any other element. Stencil provides an index page to demo a component to try it out.

When built, Stencil generates a file that can be dropped in to any project and use the component without having to worry about its inner workings. This includes other Stencil projects, regular HTML pages and also other JavaScript frameworks such as React, Vue and Angular.