<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Newton Munene on Medium]]></title>
        <description><![CDATA[Stories by Newton Munene on Medium]]></description>
        <link>https://medium.com/@newtonmunene?source=rss-dd5940b07839------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TbYI_SDpcBYJny11.</url>
            <title>Stories by Newton Munene on Medium</title>
            <link>https://medium.com/@newtonmunene?source=rss-dd5940b07839------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:18:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@newtonmunene/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Whatsapp chatbot using Node JS, Dialogflow and Twilio]]></title>
            <link>https://medium.com/@newtonmunene/creating-a-whatsapp-chatbot-using-node-js-dialogflow-and-twilio-a588e09e6131?source=rss-dd5940b07839------2</link>
            <guid isPermaLink="false">https://medium.com/p/a588e09e6131</guid>
            <category><![CDATA[whatsapp]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[twilio]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[dialogflow]]></category>
            <dc:creator><![CDATA[Newton Munene]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 09:26:04 GMT</pubDate>
            <atom:updated>2020-07-25T09:26:04.706Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m going to walk you through creating a WhatsApp chatbot using Dialogflow. I initially wanted to do this in several blog posts but I’m going to cover it all in one. Brace yourself it might be a bit long.</p><blockquote>Originally posted on my <a href="https://blog.newtonmunene.me/creating-a-whatsapp-chatbot-using-node-js-dialogflow-and-twilio-ck4xxulw3004vmus1a2gr9su1">blog</a></blockquote><h4>Prerequisites</h4><ol><li><a href="http://www.twilio.com/referral/KqKLx8">Twilio</a> account</li><li>Dialogflow account</li><li>Node Js</li><li>Javascript knowledge</li></ol><h4>Getting started</h4><p>Install the latest stable version of Node Js if you don’t have it.</p><h4>Twilio</h4><p>Visit <a href="http://www.twilio.com/referral/KqKLx8">Twilio</a> and sign up for a new account if you do not have one. You’ll be given some credits to get you started. After they are over you’ll need to pay to get more so use them wisely.</p><p>On your dashboard take note of your Account SIDand Auth Token.<br>Head over to <a href="https://www.twilio.com/console/sms/whatsapp/learn">https://www.twilio.com/console/sms/whatsapp/learn</a> and follow the instructions to connect your Whatsapp account to your sandbox. This is necessary for the sandbox environment. This is all you need for now, we’ll come back to this later.</p><h4>Dialogflow</h4><p>According to their <a href="https://cloud.google.com/dialogflow/">website</a>,</p><blockquote>Dialogflow is an end-to-end, build-once deploy-everywhere development suite for creating conversational interfaces for websites, mobile applications, popular messaging platforms, and IoT devices. You can use it to build interfaces (such as chatbots and conversational IVR) that enable natural and rich interactions between your users and your business. Dialogflow Enterprise Edition users have access to Google Cloud Support and a service level agreement (SLA) for production deployments.</blockquote><p>We will be using Dialogflow to power our chatbot. Head over to <a href="https://dialogflow.cloud.google.com/">Dialogflow Console</a> and create a new agent. I will not dive into the specifics of creating and training agents, handling entities, intents and more. That is beyond the scope of this tutorial. You can find multiple resources on this online.</p><p>After creating your agent, click on the Small Talk tab on the left and enable it. This allows our bot to respond to small talk and common phrases. You can customize the responses on the same tab. You can do this for a more personalized experience. On the right side of your Dialogflow console, there’s an input field where you can test out your bot.</p><p>When you’ve tested out your bot and are satisfied you can now follow the steps below to set up authentication for accessing your chatbot via an API.</p><ol><li>On your Dialogflow console, open settings by clicking on the gear icon next to our project name.</li><li>Take note of the Project Id that is on the General tab of the settings page under Google Project section. We’ll be using that later.</li><li>Follow the link next to Service Account.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-5PlDKSLLFAtAeUQIZ8Bg.png" /></figure><p>4. Create a new service account, give it an appropriate name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ASp_izPxLxtEMwhVRxneQ.png" /></figure><p>5. Set Dialogflow role to Dialogflow API Admin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ikzZ2e4--zCSGBDGKLhVA.png" /></figure><p>6. Create a new key and choose JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCngy-ZGESo6azIUyhpkFA.png" /></figure><p>7. Rename the downloaded JSON file to credentials.json . This is just so we can reference it easily. We will come back to this file later.</p><h4>Backend(Node Js)</h4><p>I will be using typescript in this project. You shouldn’t feel intimidated even if you haven’t used it before. You can check out <a href="https://levelup.gitconnected.com/setup-express-with-typescript-in-3-easy-steps-484772062e01">this guide</a> on how to get started with typescript and express.</p><p>Open your terminal and create a new project</p><pre>mkdir wa-chatbot &amp;&amp; cd wa-chatbot</pre><p>Initialize a new node js project inside the folder we just created and changed directory into</p><pre>npm init -y</pre><p>Install the following dev dependencies</p><ol><li>nodemon</li><li>typescript</li><li>ts-node</li><li>ts-lint</li></ol><pre>npm i -D nodemon typescript ts-node ts-lint</pre><p>Install the following dependencies</p><ol><li>express</li><li>dotenv</li><li>twilio</li><li>dialogflow</li><li>@overnightjs/core</li><li>@overnightjs/logger</li><li>body-parser</li><li>cors</li></ol><p>We’re using Overnight to stay closer to the MVC pattern and utilize Object Oriented style of programming. Read more about Overnight <a href="https://github.com/seanpmaxwell/overnight">here</a></p><pre>npm i -S express dotenv twilio dialogflow <a href="http://twitter.com/overnightjs/core">@overnightjs/core</a> <a href="http://twitter.com/overnightjs/logger">@overnightjs/logger</a> body-parser cors</pre><p>We also need to install types for these modules</p><pre>npm i -D <a href="http://twitter.com/types/node">@types/node</a> <a href="http://twitter.com/types/express">@types/express</a> <a href="http://twitter.com/types/twilio">@types/twilio</a> <a href="http://twitter.com/types/dialogflow">@types/dialogflow</a> <a href="http://twitter.com/types/body-parser">@types/body-parser</a> <a href="http://twitter.com/types/cors">@types/cors</a></pre><p>Next, we’ll create a tsonfig.json file. In the root of your project make a new file.</p><pre>touch tsconfig.json</pre><p>Copy and paste the following content inside the new file</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;baseUrl&quot;: &quot;./&quot;,<br>    &quot;outDir&quot;: &quot;build&quot;,<br>    &quot;removeComments&quot;: true,<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;target&quot;: &quot;es6&quot;,<br>    &quot;emitDecoratorMetadata&quot;: true,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;importHelpers&quot;: true,<br>    &quot;types&quot;: [&quot;node&quot;],<br>    &quot;typeRoots&quot;: [&quot;node_modules/@types&quot;]<br>  },<br>  &quot;include&quot;: [&quot;./src/**/*.ts&quot;],<br>  &quot;exclude&quot;: [&quot;./src/public/&quot;]<br>}</pre><p>Again, I will not go into the specifics for now but you can read typescript documentation for more information.<br>Next, create a tslint.json file at the root of your project and paste the following content inside.</p><pre>{<br>  &quot;defaultSeverity&quot;: &quot;warning&quot;,<br>  &quot;extends&quot;: [&quot;tslint:recommended&quot;],<br>  &quot;jsRules&quot;: {},<br>  &quot;rules&quot;: {<br>    &quot;trailing-comma&quot;: [false],<br>    &quot;no-bitwise&quot;: false,<br>    &quot;jsdoc-format&quot;: true,<br>    &quot;deprecation&quot;: true,<br>    &quot;interface-name&quot;: true,<br>    &quot;no-duplicate-imports&quot;: true,<br>    &quot;no-redundant-jsdoc&quot;: true,<br>    &quot;no-use-before-declare&quot;: true,<br>    &quot;variable-name&quot;: false,<br>    &quot;object-literal-sort-keys&quot;: false,<br>    &quot;member-ordering&quot;: true,<br>    &quot;await-promise&quot;: true,<br>    &quot;curly&quot;: true,<br>    &quot;no-async-without-await&quot;: true,<br>    &quot;no-duplicate-variable&quot;: true,<br>    &quot;no-invalid-template-strings&quot;: true,<br>    &quot;no-misused-new&quot;: true,<br>    &quot;no-invalid-this&quot;: true,<br>    &quot;prefer-const&quot;: true<br>  },<br>  &quot;rulesDirectory&quot;: []<br>}</pre><p>Let’s set up our backend structure.<br>Open your terminal and run the following commands inside the root of your project.</p><pre>mkdir src &amp;&amp; touch src/AppServer.ts &amp;&amp; touch src/start.ts</pre><p>AppServer.ts is where we will set up our express app.<br>Paste the following inside src/AppServet.ts</p><pre>import * as bodyParser from &quot;body-parser&quot;;<br>import * as controllers from &quot;./controllers&quot;;<br>import { Server } from &quot;<a href="http://twitter.com/overnightjs/core">@overnightjs/core</a>&quot;;<br>import { Logger } from &quot;<a href="http://twitter.com/overnightjs/logger">@overnightjs/logger</a>&quot;;<br>import * as cors from &quot;cors&quot;;<br>export class AppServer extends Server {<br>  private readonly SERVER_STARTED = &quot;Server started on port: &quot;;</pre><pre>constructor() {<br>    super(true);<br>    this.app.use(bodyParser.json());<br>    this.app.use(bodyParser.urlencoded({ extended: true }));<br>    this.app.use(cors());<br>    this.setupControllers();<br>  }</pre><pre>private setupControllers(): void {<br>    const ctlrInstances = [];<br>    for (const name in controllers) {<br>      if (controllers.hasOwnProperty(name)) {<br>        const controller = (controllers as any)[name];<br>        ctlrInstances.push(new controller());<br>      }<br>    }<br>    super.addControllers(ctlrInstances);<br>  }</pre><pre>public start(port: number): void {<br>    this.app.get(&quot;*&quot;, (req, res) =&gt; {<br>      res.send(this.SERVER_STARTED + port);<br>    });<br>    this.app.listen(port, () =&gt; {<br>      Logger.Imp(this.SERVER_STARTED + port);<br>    });<br>  }<br>}</pre><p>In this file, we set up our AppServer class which extends the Server class from Overnight. In the constructor, we initialise the Server class passing true as a parameter. We then head on to configure some middleware for our app. We might be receiving JSON data in our requests so we use body-parser to ensure it’s handled properly.</p><p>We then set up our controllers which we will create in a short while. After this, we define the start method which will start up the app on the port passed to it as a parameter.</p><p>Paste this into src/start.ts. This is the starting point for our application.</p><pre>import { config } from &quot;dotenv&quot;;<br>config();<br>import { AppServer } from &quot;./AppServer&quot;;</pre><pre>const appServer = new AppServer();<br>appServer.start(3000);</pre><p>At the top, we import config from dotenv and call it. We use this to configure our environment variables and load them into process.env. We also initiate a new instance of the server and call the start method passing in a port to use.</p><p>At this point, we need to set up our controllers. Create a folder inside src and call it controllers. Inside src/controllers create two files: BotController.ts and index.ts</p><p>Inside BotController.ts paste the following code</p><pre>import { Request, Response } from &quot;express&quot;;<br>import { Controller, Post } from &quot;<a href="http://twitter.com/overnightjs/core">@overnightjs/core</a>&quot;;<br>import { Logger } from &quot;<a href="http://twitter.com/overnightjs/logger">@overnightjs/logger</a>&quot;;</pre><pre><a href="http://twitter.com/Controller">@Controller</a>(&quot;api/bot&quot;)<br>export class BotController {<br>  <br>}</pre><p>You’ll notice some weird syntax just before our controller class. That’s a decorator. We use it to tell the compiler that our class is a controller. We also pass an argument which is our URL path. With this, we can now make restful requests to [SERVER]:[PORT]/api/bot.</p><p>We don’t have any routes defined yet. For Twilio, we will only need a POST route. Inside the BotController class add the following code.</p><pre><a href="http://twitter.com/Post">@Post</a>()<br>  private postMessage(request: Request, response: Response) {<br>    Logger.Info(&quot;A post request has been received&quot;);<br>    return response.status(200).json({<br>      message: &quot;A post request has been received&quot;<br>    });<br>  }</pre><p>You’ll notice another decorator which tells our compiler that the method handles POST requests.</p><p>In src/controllers/index.ts add the following code. This exports our controllers so that it will be easy to export any future controllers.</p><pre>export * from &quot;./BotController&quot;;</pre><h4>The fun stuff</h4><p>It’s time to get to the fun stuff. Let’s set up our app to communicate with Twilio and Dialogflow.<br>Create a folder called utils under src. Inside utils create two files: dialogflow.ts and twilio.ts</p><p>Inside Dialogflow.ts:</p><pre>// dialogflow.ts</pre><pre>const dialogflow = require(&quot;dialogflow&quot;);<br>const credentials = require(&quot;../../credentials.json&quot;);</pre><pre>const sessionClient = new dialogflow.SessionsClient({<br>  credentials: credentials<br>});<br>const projectId: string = process.env.DIALOGFLOW_PROJECT_ID!;</pre><pre>export const runQuery = (query: string, number: string) =&gt; {<br>  return new Promise(async (resolve, reject) =&gt; {<br>    try {<br>      // A unique identifier for the given session<br>      //const sessionId = uuid.v4();<br>      const sessionId = number;<br>      // Create a new session</pre><pre>const sessionPath = sessionClient.sessionPath(projectId, sessionId);</pre><pre>// The text query request.<br>      const request = {<br>        session: sessionPath,<br>        queryInput: {<br>          text: {<br>            // The query to send to the dialogflow agent<br>            text: query,<br>            // The language used by the client (en-US)<br>            languageCode: &quot;en-US&quot;<br>          }<br>        }<br>      };</pre><pre>// Send request and log result<br>      const responses = await sessionClient.detectIntent(request);</pre><pre>const result = responses[0].queryResult;</pre><pre>resolve(result);<br>    } catch (error) {<br>      reject(error);<br>    }<br>  });<br>};</pre><p>Here we’re importing Dialogflow and also the credentials.json file we downloaded when setting up our chatbot on Dialogflow. Remember that file? Move it to your project’s root folder. We’re the setting up a new SessionsClient using the credentials file. In our runQuery function, we’re taking in a query to send to Dialogflow and also the user’s Whatsapp number which we will use to set up a Dialogflow session unique to that user. We then send the query to Dialogflow and return the response.</p><p>In twilio.ts add the following code :</p><pre>import { Twilio } from &quot;twilio&quot;;<br>const accountSid = process.env.TWILIO_ACCOUNT_SID!;<br>const authToken = process.env.TWILIO_AUTH_TOKEN!;</pre><pre>const client = new Twilio(accountSid, authToken);</pre><pre>export const sendMessage = (to: string, from: string, body: string) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    client.messages<br>      .create({<br>        to,<br>        from,<br>        body<br>      })<br>      .then(message =&gt; {<br>        resolve(message.sid);<br>      })<br>      .catch(error =&gt; {<br>        reject(error);<br>      });<br>  });<br>};</pre><p>Here we create a new Twilio client and instantiate using our Twilio Account SID and Auth Token. We then call the client.messages.create function which takes in the number of the user, the number sending the message(in this case, the Twilio sandbox number) and also a body. We then return the message Id.</p><p>You’ve probably noticed we’ve used a few environment variables that we haven’t defined yet. In the root of your project create a .env file. Inside paste the following code and make sure to replace placeholders with appropriate values. I asked you to take note of the values required at some point in this tutorial.</p><pre>TWILIO_ACCOUNT_SID=PLACEHOLDER<br>TWILIO_AUTH_TOKEN=PLACEHOLDER<br>DIALOGFLOW_PROJECT_ID=PLACEHOLDER</pre><p>Go back to BotController.ts and replace the postMessage method with the following code.</p><pre><a href="http://twitter.com/Post">@Post</a>()<br>  private postMessage(request: Request, response: Response) {<br>    // Here we get the message body, the number to which we&#39;re sending the message, and the number sending the message.<br>    const { Body, To, From } = request.body;</pre><pre>// Here we&#39;re sending the received message to Dialogflow so that it can be identified against an Intent.<br>    runQuery(Body, From)<br>      .then((result: any) =&gt; {<br>        // We send the fulfilment text received back to our user via Twilio<br>        sendMessage(From, To, result.fulfillmentText)<br>          .then(res =&gt; {<br>            console.log(res);<br>          })<br>          .catch(error =&gt; {<br>            console.error(&quot;error is &quot;, error);<br>            Logger.Err(error);<br>          });<br>      })<br>      .catch(error =&gt; {<br>        console.error(&quot;error is &quot;, error);<br>        Logger.Err(error);<br>      });<br>    return response.status(200).send(&quot;SUCCESS&quot;);<br>  }</pre><p>Twilio hits this method when it receives a message from Whatsapp. We extract the message body, the sender, and the recipient(in this case, Twilio sandbox number). We then send the received body to Dialogflow and get a fulfilment text. We use the Twilio client we set up earlier to send back the fulfilment text to the user.</p><p>Now there’s only one more thing left to do. Open up your `package.json` and replace the scripts with the following.</p><pre>&quot;scripts&quot;: {<br>    &quot;tsc&quot;: &quot;tsc&quot;,<br>    &quot;prestart&quot;: &quot;npm run build&quot;,<br>    &quot;dev&quot;: &quot;ts-node src/start.ts&quot;,<br>    &quot;dev:watch&quot;: &quot;nodemon&quot;,<br>    &quot;build&quot;: &quot;rm -rf ./build/ &amp;&amp; tsc&quot;,<br>    &quot;start&quot;: &quot;node build/start.js&quot;<br>  },</pre><p>The full file looks this</p><pre>{<br>  &quot;name&quot;: &quot;wa-chatbot&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;build/start&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;tsc&quot;: &quot;tsc&quot;,<br>    &quot;prestart&quot;: &quot;npm run build&quot;,<br>    &quot;dev&quot;: &quot;ts-node src/start.ts&quot;,<br>    &quot;dev:watch&quot;: &quot;nodemon&quot;,<br>    &quot;build&quot;: &quot;rm -rf ./build/ &amp;&amp; tsc&quot;,<br>    &quot;start&quot;: &quot;node build/start.js&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;<a href="http://twitter.com/types/body-parser">@types/body-parser</a>&quot;: &quot;^1.17.1&quot;,<br>    &quot;<a href="http://twitter.com/types/cors">@types/cors</a>&quot;: &quot;^2.8.6&quot;,<br>    &quot;<a href="http://twitter.com/types/dialogflow">@types/dialogflow</a>&quot;: &quot;^4.0.4&quot;,<br>    &quot;<a href="http://twitter.com/types/express">@types/express</a>&quot;: &quot;^4.17.2&quot;,<br>    &quot;<a href="http://twitter.com/types/node">@types/node</a>&quot;: &quot;^13.1.2&quot;,<br>    &quot;<a href="http://twitter.com/types/twilio">@types/twilio</a>&quot;: &quot;^2.11.0&quot;,<br>    &quot;nodemon&quot;: &quot;^2.0.2&quot;,<br>    &quot;ts-lint&quot;: &quot;^4.5.1&quot;,<br>    &quot;ts-node&quot;: &quot;^8.5.4&quot;,<br>    &quot;typescript&quot;: &quot;^3.7.4&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;<a href="http://twitter.com/overnightjs/core">@overnightjs/core</a>&quot;: &quot;^1.6.11&quot;,<br>    &quot;<a href="http://twitter.com/overnightjs/logger">@overnightjs/logger</a>&quot;: &quot;^1.1.9&quot;,<br>    &quot;body-parser&quot;: &quot;^1.19.0&quot;,<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;dialogflow&quot;: &quot;^1.0.0&quot;,<br>    &quot;dotenv&quot;: &quot;^8.2.0&quot;,<br>    &quot;express&quot;: &quot;^4.17.1&quot;,<br>    &quot;twilio&quot;: &quot;^3.39.1&quot;<br>  }<br>}</pre><p>You can run npm install again in case I missed any dependencies. We also need to set up nodemon. Create a nodemon.json in your project’s root folder and paste the following inside.</p><pre>{<br>  &quot;watch&quot;: [&quot;src&quot;],<br>  &quot;ext&quot;: &quot;ts&quot;,<br>  &quot;ignore&quot;: [&quot;src/public&quot;],<br>  &quot;exec&quot;: &quot;NODE_ENV=development ts-node src/start.ts&quot;<br>}</pre><p>You can now run npm run dev:watch and see if your project runs successfully. Next, we need to expose our local server. <a href="https://ngrok.com/">Ngrok</a> is one of the best open-source solutions but you can use whatever you prefer.</p><p>Copy your exposed server URL and open <a href="https://www.twilio.com/console/sms/whatsapp/sandbox">Twilio Whatsapp Sandbox</a>. Replace the URL in <strong>WHEN A MESSAGE COMES IN</strong> with your exposed URL. Don’t forget to add the path to our bot controller. i.e. /api/bot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVbpPKzS2AkwJWJbwl-jjw.png" /></figure><p>Save the new changes and you can now send a message to the Twilio Sandbox Number and you’ll see the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRnZca4JIICYNnDvfuFCEw.jpeg" /></figure><p>Here’s some homework for you. Create a new controller to handle POST requests and pass the URL to the STATUS CALLBACK URL input on the <a href="https://www.twilio.com/console/sms/whatsapp/sandbox">Twilio Whatsapp Sandbox</a>. Be creative and be notified when a user reads your message and when it’s delivered.</p><p>The full source code can be found here <a href="https://github.com/newtonmunene99/wa-chatbot](https://github.com/newtonmunene99/wa-chatbot)">https://github.com/newtonmunene99/wa-chatbot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a588e09e6131" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# Stencil as a design system tool.]]></title>
            <link>https://medium.com/@newtonmunene/stencil-as-a-design-system-tool-4720a87ccdac?source=rss-dd5940b07839------2</link>
            <guid isPermaLink="false">https://medium.com/p/4720a87ccdac</guid>
            <category><![CDATA[stenciljs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[stencil]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Newton Munene]]></dc:creator>
            <pubDate>Fri, 07 Jun 2019 09:39:35 GMT</pubDate>
            <atom:updated>2020-05-27T09:46:44.267Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*f6GA9hMEXK5hT3ddZ9SI_g.png" /></figure><h3>Stencil as a design system tool.</h3><h4>Introduction</h4><p>If you are a product designer you’ve probably heard of design systems. It’s an important aspect in your field. Some front end devs already know what design systems are and are probably using them. We have all seen companies like Google, Uber, Airbnb talk about design systems and we’re often left wondering, what the heck is all the fuss about.</p><p>A design system is a group/collection of components built using strict guidelines and clear standards. According to [Stencil Js](<a href="https://stenciljs.com/docs/what-is-design-system">https://stenciljs.com/docs/what-is-design-system</a>), A Design System(DS from now on) consists of UI components and a clearly defined visual style, released as both code implementations and design artefacts. When adopted by all product teams, a more cohesive customer experience emerges. Let’s break this down.</p><p>As part of a design team at a company, you seat down to discuss the design of your next product. You quickly realise that your next product will not have the same visual appeal as your previous product, and your previous product looks nothing like your first product. The problem here is that your design is not consistent. The mobile team is creating something totally different from the web team. This is where a design system comes into play. Having a clear guideline on what your digital products should look like is really important. Here’s why:</p><ol><li>Saves Time</li></ol><p>When you already a DS implemented you eliminate the time taken to draft up designs and mock-ups for products. When you already have something to reference everything moves quick.</p><p>2. A fluent design</p><p>The human brain automatically feels comfortable around familiar surroundings. Let’s take a logo for example. When a human sees a logo they are familiar with they will immediately recognise the entity associated with it. Same as Google’s material design or bootstrap. In the same way, if you have consistent designs on your products users can immediately relate.</p><p>3. Maintenance</p><p>It’s easy to maintain your product’s design because the components are modular and reusable. You just have to update the component and you don’t have to dive into your messy javascript code. *We all write messy code at times.*</p><p>And that’s just the tip of the metaphorical iceberg. Do I have you hooked yet? Here’s how you can implement a DS.</p><ol><li>Evaluate your current design.</li></ol><p>Take a look at your current design and decide what you want to keep and what you’d like to discard. Add whatever else is missing while at it.</p><p>2. Implement a design language/guideline.</p><p>This includes colour, fonts and typography, spacing and margins, shapes etc. Like rounded corners, some unique font, 5 px margins, the colour yellow? Implement that.</p><p>3. Decide on a pattern.</p><p>You already have what you would like to keep and a design language. Now agree on a pattern: Call to action buttons, active and inactive elements, positioning of elements, font size etc.</p><p>4. Document your components.</p><p>A wide range of people will be using your DS, so make sure the documentation is easy to follow and comprehensive.</p><p>Time to get rid of the bore. Let’s get into the good stuff.</p><h4>Stencil JS</h4><p>This is a tool created by the team at [Ionic](<a href="https://ionicframework.com/">https://ionicframework.com/</a>) to help them build web components for Ionic Framework internally. They eventually realised Stencil’s potential and made it open to the public. It’s a tool for creating web components or even whole web apps. Paired with Ionic 4 which is now universal(works with any javascript framework or no framework at all thanks to stencil js), you can build a fully optimized Progressive Web App. I will not get into web components in this post but they are what Stencil is created to achieve. I’ve been using Stencil since it’s early beta days and just yesterday on June 6 2019, they released stencil one 🎊🎉🎆. Read more about it on their blog, <a href="https://ionicframework.com/blog/introducing-stencil-one-1-0-0/">https://blog.ionicframework.com/</a></p><h4>Prerequisites</h4><ul><li>Basic Typescript knowledge</li><li>Node Js</li><li>NPM 6 or higher</li></ul><h4>Let’s get started.</h4><p>Fire up your terminal 💻 and run:</p><pre>npm init stencil</pre><p>You’ll be presented with a prompt to choose what kind of project you would like and to name it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*F35-bl94gcedRsBebl6C5Q.png" /></figure><p>I’d like to make a simple web component. Choose that and give it a name. I called mine `ds-tutorial`. `cd` into your project.</p><pre>cd ds-tutorial</pre><p>There’s a lot of files and folders here so let’s see what’s important.</p><ol><li>src — This is your working directory, your app lives here and this is where you will be writing most if not all of your code.</li><li>src/components — This is where your component(s) will be. There’s already a default component in there.</li><li>src/index.html — This is your app’s entry HTML file. Open it and you’ll find the default component mentioned above used.</li><li>package.json — Defines your dependencies and some other useful information used by package providers and stencil.</li><li>stencil.config.ts — This contains the configuration for your stencil project. You can add service workers, plugins, generate docs and more. Read more about it <a href="https://stenciljs.com/docs/config">here</a></li></ol><p>The rest must be familiar to you. Stencil uses TSX, which is typed JSX. JSX is a syntax extension to javascript and is common in React. It should not scare you off. It’s fairly simple to use. It allows us to write our HTML inside javascript files.</p><p>Open up your project in a text editor. Visual Studio Code has awesome syntax highlighting and tooling. Navigate to src/components/my-component/my-component.tsxand change the code to</p><pre>import { Component, Prop, h } from &#39;<a href="http://twitter.com/stencil/core">@stencil/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>  tag: &#39;my-component&#39;,<br>  styleUrl: &#39;my-component.css&#39;,<br>  shadow: true<br>})<br>export class MyComponent {<br>  /**<br>   * Your name<br>   */<br>  <a href="http://twitter.com/Prop">@Prop</a>() name: string;</pre><pre>render() {<br>    return &lt;div&gt;Hello, World! I&#39;m {this.name }&lt;/div&gt;;<br>  }<br>}</pre><p>There’s a handful going on here. If you’ve used angular before you’ll be familiar with decorators.</p><pre><a href="http://twitter.com/Component">@Component</a>({<br>  tag: &#39;my-component&#39;,<br>  styleUrl: &#39;my-component.css&#39;,<br>  shadow: true<br>})</pre><p>This decorator provides metadata about our component to the Stencil compiler. I won’t get into the details but you can research on decorators.</p><ul><li>`tag` defines the HTML tag of your web component.</li><li>`styleUrl` defines the path to your stylesheet.</li><li>`shadow` determines if your component will use native shadow-dom encapsulation or not.</li></ul><p>Inside your class, there’s another decorator</p><pre><a href="http://twitter.com/Prop">@Prop</a>() name: string;</pre><p>This decorator defines properties which should be passed to our component. Think of these properties as attributes. There’s a ton of other decorators which you can read about <a href="https://stenciljs.com/docs/decorators">here</a>.</p><p>There’s finally the render function. This function outputs a tree of components that will be drawn to the screen.</p><pre>render() {<br>    return &lt;div&gt;Hello, World! I&#39;m {this.name }&lt;/div&gt;;<br>}</pre><p>Save this file and open src/index.html.Just after the opening body tag, you’ll find your component. Make sure the tag matches that in your my-component.tsx</p><pre>&lt;my-component name=&quot;Your Name&quot;&gt;&lt;/my-component&gt;</pre><p>Remember the name property, just like a normal attribute right 😃? Save this file and go back to your console. Make sure you’re in the project’s root directory and run:</p><pre>npm start</pre><p>Now watch the magic happen. Try changing the value of the name attribute in index.htmland save. Watch what happens. The changes will be reflected immediately. And it’s crazy fast. Now add some styling to src/components/my-component/my-component.css and watch. Play around with these three files. When you’re done go to the console and run:</p><pre>npm run build</pre><p>This builds your component(s) for production and saves it in the dist folder. You can change this in stencil.config.ts. You can now publish this to NPM or some other place. Add a few more components in the components folder and you have a collection of web components, a Design System 😀. Stencil handles all the hard things in the background so you can focus on the easy stuff.</p><h4>Finalizing</h4><p>You can always visit the stencil website for more advanced concepts and usage. This was just to get you started with Stencil. There’s so much more you can do using stencil. I’ve not even covered a quarter of what stencil is capable of. Try it out, push your imagination to the limit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4720a87ccdac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>