Getting Started with StencilJS - A Compiler for Web Components

Getting Started with StencilJS - A Compiler for Web Components

Stencil is a compiler that generates Web Components developed by the Ionic team. Stencil combines the best concepts of the most popular frameworks into a simple build-time tool.

Stencil is a compiler that generates Web Components developed by the Ionic team. Stencil combines the best concepts of the most popular frameworks into a simple build-time tool.

Stencil takes popular features such as the Virtual DOM, Typescript and JSX to create standard-based Web components which can be used with every popular frontend framework out of the box (Angular, React, Vue).

The main goal of this article is to give a quick overview of the Stencil framework and how to use it to build Web Components. We will also look at how we can build our component so it can be use in the most popular frontend frameworks (Angular, React, Vue, Ember).

So, without wasting any further time, let’s get started.

Setup StencilJS

Before we can start creating a component we first need to set up our Stencil development environment. For that, you need to have Node.js installed and then need to clone the starter project.

git clone https://github.com/ionic-team/stencil-component-starter stencil-starter
cd stencil-starter
git remote rm origin
npm install

These commands clone the stencil-component-starter project and save it in the local storage. After that, we just move into the folder and install all the dependencies of the project.

The starter project provides a standard Node.js development environment including some basic configurations, a development server and some example components.

Now that we have completed the basic stencil setup we can start creating our first component.

Creating a web component

Stencil components are built using *JSX *and Typescript. Therefore, you should be very familiar with these two technologies before going further.

To create our component we first need to create a new directory in src/component and than create the two needed files.

cd src/components
mkdir sample-component && cd sample-component
touch sample-component.tsx && touch sample-component.css

The CSS file will remain blank for the moment. The .tsx file will contain following code:

import { Component, h } from '@stencil/core';@Component({
 tag: 'sample-component',
 styleUrl: 'sample-component.css',
 shadow: true
})
export class SampleComponent{
 render() {
  
return (
   <div>
   <h1>Sample Component</h1>
   </div>
  );
 }
}

Now let’s walk through the bit of code we just wrote:

  • In order to define a Stencil component we need to declorate our classes with the @Component declarator previously imported from stencil/core. This declarator allows us to define some basic information about our component like the tag that will later be used to call our component (In this case ). Next up we defined the styleUrl property which enables the css design and points to the css file we previously created.
  • The render() function describes the appearance of our component using JSX syntax. In this example, it consists of a div with a h1 tag insight.
Testing a web component

Now that we have defined our first component let’s take a look at how we can test our component by using it in our index.html. For that we just remove the standard component and import our own one.

<!DOCTYPE html>
<html 
dir="ltr" lang="en">
<head>
 <meta 
charset="utf-8">
 <title>Stencil Starter App</title>
 <meta 
name="Description" content="Welcome to the Stencil App Starter. You can use this starter to build entire apps all with web components using Stencil!">
 <meta 
name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
 <meta 
name="theme-color" content="#16161d">
 <meta 
name="apple-mobile-web-app-capable" content="yes">
 <meta 
http-equiv="x-ua-compatible" content="IE=Edge">
 <script 
type="module" src="/build/app.esm.js"></script>
 <script 
src="/build/sample-component.js"></script>
</head>
<body>
 <sample-component></sample-component>
</body>
</html>

Here we imported our component by including the sample-component.js script and than use it by adding the tag of our component. After that we can start our development server using the npm start command.

Now you should see the rendering of our basic component on localhost:3333.

Properties

Properties are dynamic parameters that are used to pass down data from parent components to any of their child components. Properties are declared using the @Prop declarator. They can have many different types including number, boolean, string, Object or an Array.

Defining properties

Let’s change our sample component to make it a little bit more dynamic.

import { Component, h, Prop } from '@stencil/core';@Component({
 tag: 'sample-component',
 styleUrl: 'sample-component.css',
 shadow: true
})
export class SampleComponent{
 @Prop() text: string = 'World'
 
 render() {
  
return (
   <div>
    <h1>Hello {
this.text}</h1>
   </div>
  );
 }
}

Here we first import the @Prop() declarator and the use it to define a string parameter with a default value. Than we use the parameter that is passed down in our render() function using databinding.

Using Properties

Now that we have defined the property in our component let’s look at how we can use it in our markup language.

<sample-component text="Test"></sample-component>

By defining the property in the markup we map the value to the text attribute and are able to use it in our component.

When we visit the website now we should see the dynamic parameter being displayed.

Properties can also be accessed via Javascript from the element.

const sampleComponent = document.querySelector('sample-component');
const test = sampleComponent.test

Property mutability

Properties are immutable from inside the component logic by default. Once a value is set by the user it can’t be updated internally. However, it’s possible to manually allow a Property to be mutable from inside the component by declaring it mutable.

@Prop({ mutable: true }) name: string = 'Name';

States

The @State declarator is used to manage internal data for a component. This means that users can not modify the data but the component can change it as he sees fit.

@State() isActive = falseupdateStatement() {
 
this.isActive = !this.isActive
}

State should only be used if the component needs to re-render when the data is changed. If that’s not the case it’s a good practice to avoid the @State declarator and use normal internal states instead.

internalState: boolean = true

Events

Events in Stencil are used to emit data and events from our component. The @Event() declarator is used to define custom DOM events.

Creating a DOM event:
@Event() active: EventEmitter;checkboxCompletedHandler(checkbox: Checkbox) {
 
this.active.emit(checkbox);
}

The code above will dispatch a custom DOM event called active.

Listening to the event:

Now that we have defined our first custom DOM event let’s take a look at how we can setup a listener which get’s called when the events is emitted.

import { Listen } from '@stencil/core';@Listen('active')
activeStateHandler(event: CustomEvent) {
 console.log('Received the custom active event: ', event.detail);
}

The @Listen() declarator can also be used to listen to normal DOM events like onClick or keyDown.

@Listen('click', { capture: true })
handleClick(ev) {
 console.log('click');
}

Defining events in JSX:

We can also bind listeners to events directly in our JSX code. This works similar to normal DOM events.

<sample-component text="Test" active={ev => this.someMethod(ev)}></sample-component>

You can also define normal DOM events like you can in normal HTML.

<input onChange={(event: UIEvent) => this.inputChanged(event)}/>

Here we define an onChange event listener and call the inputChanged function when the event is triggered.

Methods

The @Method() declarator is used to expose methods to the public API. All methods decorated with the @Method() can be called directly from the element, ie. they are intended to be callable from the outside.

Defining Methods:

Stencils architecture is async at all levels which means that public functions have to be defined async as well even if they don’t return a promise. They also need to be declared with the @Method() declarator to make them publicly accessible.

import { Method } from '@stencil/core';@Method()
async getState() {
 // Get the state of the item
}

Private methods on the other hand don’t have to be async and do not have the @Method() declarator.

getState() {
 
return this.isActive
}

Calling Methods:

Public methods can be called by getting the element from the DOM and calling the method on the reference. Here is an example:

const component = document.querySelector('sample-component')
const state = component.getState()

Note: Methods are not immediately available on a component they have to be loaded/hydrated by Stencil before you can use them.

Elements

The @Element declarator enables us to get a reference of the components host element. This can be helpful if you want to manipulate the host during runtime.

Now let’s look at an example use case of the @Element declarator:

@Element() messageDiv: HTMLElement;showMessage() {
 
this.messageDiv.style.display = 'block';
};

In this example we get the host component using the @Element() declarator and than change it’s style in a private function.

Lifecycle

Stencil component have numerous lifecycle methods which can be used to know which state the component is in e.g load or unload. They can be added to your components to hook methods to the right time events.

Here is a list of the most important lifecycle events in Stencil:

  • componentWillLoad() — Before rendering
  • componentDidLoad() — After rendering
  • componentWillUpdate() — Before updating
  • componentDidUpdate() — After updating
  • componentDidUnload() — After unmounting

Now let’s look at an example implementation of a lifecycle method.

componentDidLoad() {
 console.log('Component successfully loaded')
 
// Do something
}

Here we define the componentDidLoad() lifecycle function which will be called right after the component was fully loaded and the first render occurt.

If you want a full list of all the available lifecycle events you can visit the official documentation.

Nesting

Stencil also provides the functionality to nest components in each other by adding the HTML tag to the JSX code. Since the components are just plain HTML nothing needs to be imported to use them in another component.

Here is an simple example of using a component within another component:

Child Component:

import { Component, Prop, h } from '@stencil/core';@Component({
 tag: 'embedded-component'
})
export class EmbeddedComponent {
 @Prop() text: string = 'Hello World';
 render() {
  
return (
   <div>{ 
this.text }</div>
  );
 }
}

Parent component:

import { Component, h } from '@stencil/core';@Component({
 tag: 'parent-component'
})
export class MyParentComponent {
 render() {
  
return (
   <div>
    <embedded-component 
text="Hello Stencil"></embedded-component>
   </div>
  );
 }
}

In this example the parent component includes a reference to the in the render function.

Unit testing

Now that we know how to define and use components let’s look at how we can test them using Jest as our Test runner and assertion library (Jest is the default testing framework for Stencil).

Instantiation our component:

In Unit Testing you normaly instantiate your component before a test. This is normaly done by importing the component you want to test and instantiating it manually. This is not necessary in Stencil because the components are plain Javascript. This gives us the abbility to instantiate them using the new keyword.

import {SampleComponent} from './sample-component'describe('sample-component', () => {
 it('builds', () => {
  const sampleComponent = new SampleComponent
  expect(sampleComponent).toBeTruthy();
});
})

In this example we instatiated our component using the new keyword and than checked if it build successfully using the toBeTruthy() function provided by Jest.

Most of the time we will need to instantiate the component before every test. That can be done using the beforeEach() function which is also provided by Jest.

let sampleComponent;
beforeEach(() => {
 sampleComponent = new SampleComponent();
});

  • Now that we have an instance of our component you can start testing it using the Jest framework.
Preparing for Production

Now that we have a fully functional component let’s prepare it for a production build. For that we just need to complete the following steps:

Name changes:

First of all, we need to update the names in our project in the stencil.config.ts and package.json files.

We can do so by adding the namespace parameter in the stencil.config.ts and changing the name parameter in package.json.

// stencil.config.ts
export
 const config: Config = {
 namespace: 'sample-component',
 ...
};
// package.json
"name": "sample-component",

Picking an output target:

Stencil functions as a compiler which means that it can generate different kinds of builds depending on how the component will be used. Let’s look at the different targets that are available.

  • dist — For distribution
  • www — Websites
  • docs-readme — Documentation readme files formatted in markdown
  • docs-json — Documentation data formatted in JSON

Now that we know the different kinds of output targets let’s look at an example configuration in our stencil.config.js file.

export const config: Config = {
 outputTargets: [
 {
 type: 'dist'
 },
 {
 type: 'www'
 }
 ]
};

Building the project:

Now that we have completed the preparations for production let’s continue by building our project using the npm run build command.

After a few seconds you should see a dist folder in the project with the following folders and files:

  • sample-component.js — The entry point to the component
  • sample-component — Contains the compiled code of our component
  • types — Contains the Typescript types and is useful when using the component in Typescript projects
  • collection — Allows to share components more effectively

These folders are used for different types of production scenarios. The minimal code required to use the component with HTML and vanilla Javascript consists of the sample-component.js file and the sample-component folder.

For a detailed overview of how you can use your component in vanilla javascript and popular web framework you can look at the official documentation.

Conclusion

You made it all the way until the end! Hope that this article helped you understand the basics of Stencil.js and why it is so useful.

If you have found this useful, please consider recommending and sharing it with other fellow developers. If you have any questions or feedback, let me know in the comments down below.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI


Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]