/ stencil

Faster Web Applications Using Stencil

Conceptually, Web Components are a thing of the now. The majority of web frameworks now use a component based model because it's a convenient way to separate concerns, as well as providing reusable, declarative UI.

Until recently libraries such as Ionic have had to choose an underlying framework and hook into that. This means that if you're looking to target every other developer that doesn't want to use Angular, you can't!

Embracing the idea of cross-platform should also be embracing the idea of modularity and developer choice, all of the things the web component model brings... "There's an element for that".

Let's take a look at what the Ionic team are working on:

Stencil Starter

To clone the Stencil starter project, we can type the following in our terminal:

git clone https://github.com/ionic-team/stencil-starter

This will clone the stencil-starter repository and we'll be able to open this up inside of Visual Studio Code.

Stencil Config

If we look at stencil.config.js we've got some configuration options, as well as an array to bootstrap any new components that we write:

exports.config = {
  publicPath: 'build',
  bundles: [
    { components: ['my-name'] }
  ]
};

exports.devServer = {
  root: 'www',
  watchGlob: '**/**'
}

Stencil Components

The my-name component referenced inside of our config can be found inside of components\my-name my with the .tsx extension. If you've used React, Preact or any other library using .jsx, you'll have come into contact with this before.

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

@Component({
  tag: 'my-name',
  styleUrl: 'my-name.scss',
})
export class MyName {
  @Prop() first: string;
  @Prop() last: string;

  componentWillLoad() {
    console.log("Loading...");
  }

  render() { 
    return (
      <p>
        My name is {this.first} {this.last}
      </p>
    );
  }
}

It uses the best of both worlds, TypeScript decorators to reduce boilerplate and complexity, as well as the standard component model that many are used to.

Similar to Angular, when we use the @Component above our Class, we're letting Stencil know that this class is a component we're creating.

If we take a look at the @Prop() in more detail, we can see that it's a read only input which we're using to output inside of the render function.

As well as using @Prop(), we can also use @State() to hold local state that isn't placed on an element for input.

@State() myVariable: string;

Conclusion

I'm super excited with things to come from the Ionic team. I'm looking forward to using Stencil in my own projects as I can imagine there'll be significantly less overhead. This means a lot for the future of the web with more libraries becoming framework agnostic.

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More