<?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 ankita srivastava on Medium]]></title>
        <description><![CDATA[Stories by ankita srivastava on Medium]]></description>
        <link>https://medium.com/@srivastavaankita080?source=rss-ddb9d07b4919------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BLuyZry-R0MaihpSmTL_-A.png</url>
            <title>Stories by ankita srivastava on Medium</title>
            <link>https://medium.com/@srivastavaankita080?source=rss-ddb9d07b4919------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:04:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srivastavaankita080/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[Javascript Engine & Runtime]]></title>
            <link>https://srivastavaankita080.medium.com/javascript-engine-runtime-ae9d392c170a?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9d392c170a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[jsenginge]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[js-runtime]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Sat, 16 Sep 2023 17:22:15 GMT</pubDate>
            <atom:updated>2023-09-16T17:22:15.482Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a conversation between two coworkers who are working on a front-end project using Javascript.</p><p><strong>Jill: </strong>Hey Jack, I am new to the frontend world, as I have been working on backend projects for the past few years. When I try to comprehend Javascript after working on backend projects, I am confused as to how Javascript works internally versus how the backend languages used to operate. Could you please help me understand how Javascript executes my code?</p><p><strong>Jack:</strong> Hey, Jill, of course! Javascript is a beautiful language, and you will be amazed to see how well it manages the code internally and executes. But to understand how Javascript executes the code, you first need to know about the JS Engine, which does all these magic for us.</p><p><strong>Jill:</strong> Ok. What is the JS Engine? Is it something similar to what other programming languages used to have, like the JVM in Java?</p><p><strong>Jack:</strong> Yeah, somewhat similar. You can consider JS Engine as another program that is running your Javascript code. We run our source code on different browsers, and all these browsers use different JS engines to run the source code. The most famous one is <strong>Chrome’s V8 Engine</strong>, which is used by the <strong>Chrome browser</strong> and by <strong>NodeJs</strong>( using which we can build server-side applications using Javascript).</p><p><strong>Jill:</strong> Interesting. I was not aware of this. So how does this JS engine work then?</p><p><strong>Jack:</strong> Yes, I will tell you how the JS engine works, but before that, you need to understand the internal layout of the JS engine, which is really important.</p><p><strong>JS Engine Internals:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t4r4HyvychLPYvMx.png" /></figure><p><strong>Jack:</strong> You can see two things in this picture, i.e., <strong>call stack</strong> and <strong>memory heap</strong>.</p><ol><li><strong>Call Stack:</strong> This is the place where our Javascript code gets executed, and a lot of people also call it <strong>execution context</strong>.</li><li><strong>Heap:</strong> This is the place where our code objects get stored.</li></ol><p><strong>Jill:</strong> You mentioned that the JS code gets executed in the <strong>execution context</strong>; how does the JS source code execution happens from start?</p><p><strong>Jack:</strong> Ok, So let’s understand how Javascript code gets compiled first. By definition, Javascript is an interpreted language, and this was true in earlier versions of Javascript. With the evolution of modern Javascript, this has changed.</p><p>So you might be aware of:</p><ol><li><strong>Compilation</strong> — where all the source code gets compiled at once and then can be sent for execution later on when required.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fIf6dn_A_g61nC0g.png" /></figure><p><strong>2. Interpretation</strong> — where each line gets converted to machine code and sent for execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uvb2CUFKfcm100sb.png" /></figure><p><strong>3. JIT: </strong>The<strong> </strong>JS Engine does not only do compilation or interpretation. In fact, it’s a mix of both worlds. Here comes the <strong>JIT (just in time) compiler</strong>, which is a combination of compilation and interpretation in that it will compile all of the code to machine code and then immediately deliver the generated machine code for execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qpSc0h0ynsIE-CPt.png" /></figure><p><strong>Jill:</strong> Oh, so Javascript does both things internally, and I guess this will also help in improving the performance.</p><p><strong>Jack:</strong> Yes, but there is more. Let’s see how these things exactly happen in the JS Engine, right from the time you start the code execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*umVL1wWy3AyR8cK2.png" /></figure><p><strong>Step 1:</strong> When you start the source code processing, <strong>parsing</strong> happens as the first step. In this step, your source code gets converted to an AST (<strong>Abstract Syntax Tree</strong>), which you can see on the right side of the above picture.</p><p><strong>Step 2:</strong> Once the AST gets generated, the JS engine sends the AST as the output from the first step to the second step, i.e., <strong>compilation</strong>. Here, JS Engine uses the JIT compiler and generates machine code from the AST.</p><p><strong>Step 3:</strong> Now the generated machine code is being sent to the third step, i.e., <strong>execution</strong> (which happens inside the call stack), and the machine code gets executed.</p><p><strong>Jill:</strong> So, the simple JS code gets converted to AST, which then gets converted to machine code, and that gets executed, and we are done, right?</p><p><strong>Jack:</strong> Not yet. Ever wondered how Javascript is so fast and smooth even though it compiles all the source code at once and gives it execution?</p><p>An intermediate phase is called as <strong>optimization</strong>. When the AST is sent to the compilation phase by the JS Engine, the JIT compiler generates the bare minimum machine code feasible and sends it to the execution phase. Javascript code runs faster this way, and then it optimizes the machine code and executes it again, making Javascript fast and seamless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MAZqcL92VhjoDHOH.png" /></figure><p><strong>Jill:</strong> Brilliant. What a great strategy to improve performance! Can we explore or debug these steps in the browser, e.g., how parsing and other steps are happening?</p><p><strong>Jack: </strong>Unfortunately not. Steps like <strong>parsing</strong>, <strong>compilation</strong>, and <strong>optimization</strong> happen in special threads that are not available for us to access, but the <strong>execution</strong> phase is available for us to check in the browser (the call stack and heap).</p><p><strong>Jill: </strong>Oh nice. This is helpful to understand how JavaScript has so many steps before actually showing the result. Is this all, or do we have other parts of the browser that help the JS engine work smoothly?</p><p><strong>Jack:</strong> Yes, you guessed it right. The JS engine is the heart of the browser for executing the source code. There are other things available inside the browser to help the JS engine, and collectively they are called the <strong>Javascript Runtime</strong>.</p><p><strong>Jill: </strong>Great. Can you tell me a little bit about it as well.</p><p><strong>Jack:</strong> Sure. Other than the JS Engine, the browser also has three more important parts so that the JS code works properly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gu_cZsU1i0QLUgoY.png" /></figure><p>As you can see in the above image:</p><ol><li><strong>Web API:</strong> These are the functionalities provided to the JS engine but are not available as part of the JS engine; instead, they are accessible on the <strong>window</strong> object (global object), e.g., the <strong>DOM API</strong>, <strong>Fetch API</strong>, and even the <strong>console.log</strong> that you use for printing statements is not coming from Javascript or JS Engine; instead, it’s part of this Web API and available in a <strong>window</strong> object.</li><li><strong>Callback Queue:</strong> This is the queue that holds all the callback functions from the DOM event listener, like the <strong>onClick</strong> function, until execution of that function gets triggered.</li><li><strong>Event Loop:</strong> This event loop is very important for the callback function’s execution as it takes the callback function from the callback queue and puts it in the call stack (when the call stack gets empty) for execution.</li></ol><p><strong>Jill:</strong> Woah. That’s a lot of information I was not aware of. I was astonished to learn that console.log, as well as the other information you gave, is not part of the JS engine. This is quite useful. So all JS runtime, including JS Engine, Web API, callback queue, and event loop, is like that, right? Are our browsers all the same?</p><p><strong>Jack:</strong> Yes, all browsers have similar runtimes. They might use different JS engines, as I told you, Chrome uses V8 as its JS engine, but their runtime is the same. But at the same time, V8 is also getting used by <strong>NodeJs</strong>, and its runtime is a little different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hFtL8R0pn45orVCq.png" /></figure><p>Node JS Runtime does not have a Web API as it is not a browser, and everything else, like the JS Engine, callback queue, and event loop, is the same.</p><p><strong>Jill:</strong> Thanks Jack. That’s a lot of insights I got about Javascript internals. I learned a lot from it, and hopefully we will be catching up more often to have some more amazing and thoughtful discussions.</p><p><strong>Jack:</strong> My pleasure. Definitely, we can catch up more often.</p><p>That concludes my discussion of the <strong>JS Engine and its runtime</strong>. I hope it will be both helpful and insightful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9d392c170a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your Create React App using Vite from scratch]]></title>
            <link>https://srivastavaankita080.medium.com/build-your-create-react-app-using-vite-from-scratch-2319e8af69a1?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/2319e8af69a1</guid>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Tue, 23 May 2023 20:57:49 GMT</pubDate>
            <atom:updated>2023-05-23T20:57:49.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBSqw2hm67ddA86iR1xLpw.jpeg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.telerik.com%2Fblogs%2Fwhat-is-react-used-for&amp;psig=AOvVaw2BMsBrzoOFW43SuIJ01dCU&amp;ust=1684961412412000&amp;source=images&amp;cd=vfe&amp;ved=0CBEQjRxqFwoTCKDg4ciojP8CFQAAAAAdAAAAABAs">https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.telerik.com%2Fblogs%2Fwhat-is-react-used-for&amp;psig=AOvVaw2BMsBrzoOFW43SuIJ01dCU&amp;ust=1684961412412000&amp;source=images&amp;cd=vfe&amp;ved=0CBEQjRxqFwoTCKDg4ciojP8CFQAAAAAdAAAAABAs</a></figcaption></figure><p><strong>create-react-app</strong> is one of the famous libraries that we have been using to create a new React application by running the below command:</p><pre>npx create-react-app my-app</pre><p>But CRA comes with <strong>Webpack</strong> as a bundler tool, and if you want to change the bundler tool, you need to eject the CRA app and do everything from scratch with the boilerplate code. So let’s say you want to build a React app using some other bundler tool; do you really think using CRA would be a good option just for boilerplate code? Personally, I feel that if you want to change the build tool and other configurations that come with CRA, it will not be a wise decision to use CRA. But if you still want to use CRA, understand what it’s doing behind the box so that you can eject it and make the changes accordingly.</p><p>This was the time when I started looking at, what CRA gave us out of the box and started building my own version of CRA. I would like to share my learnings with you all while building this version of CRA.</p><p>If you are in a hurry and just want the steps with no description, you can follow the git commits in this repository where I have implemented create-react-app-clone, but if you want to understand each step and what they are actually doing behind the scenes, I will suggest reading this blog.</p><p><a href="https://github.com/sankita15/create-react-app-clone/commits/main">Commits · sankita15/create-react-app-clone</a></p><p>So, Let’s get started:</p><p><strong>Step 1:</strong> We will start with creating a simple <strong>HTML</strong> file with a <strong>title</strong> and <strong>heading</strong> using the <strong>title</strong> and <strong>h1</strong> tag, something like this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Hello World by HTML!&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Step 2:</strong> So, now you need to add some <strong>Javascript</strong> to the above <strong>HTML</strong> file to manipulate the body. We are still showing a header with a message as in the previous <strong>HTML</strong> file, but this time using <strong>JavaScript</strong>. For this, you can add a <strong>script</strong> tag and add your JS code like below:</p><pre>&lt;!--Step 2--&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>&lt;script&gt;<br>    const heading = document.createElement(&quot;h1&quot;)<br><br>    heading.innerHTML = &quot;Hello World by Javascript&quot;;<br><br>    const root = document.getElementById(&quot;root&quot;)<br><br>    root.append(heading)<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>In the above file, you are doing the same thing, but instead of using the html <strong>h1</strong> tag, you are using the javascript <strong>createElement</strong> API to create a <strong>h1</strong> element. Once the <strong>h1</strong> element is created, you need to append it to the div id where you want to display it. Simple, isn’t it? Just basic Javascript 😊</p><p><strong>Step 3:</strong> Moving on to the third step, where you will be introducing <strong>React</strong> to our project, As we started with an HTML file, we can use <strong>CDN links</strong> to use React in this HTML file.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>&lt;script crossorigin src=&quot;https://unpkg.com/react@18/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>&lt;script crossorigin src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>    const heading = React.createElement(&quot;h1&quot;, {}, &quot;Hello World by React&quot;)<br><br>    const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;))<br><br>    root.render(heading);<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>As you can see, we have used <strong>CDN links</strong> for <strong>React</strong> and <strong>React DOM</strong>, but these are only for development purposes. As per the React docs, you should use the minified and optimized production version; links can be found in the <a href="https://legacy.reactjs.org/docs/cdn-links.html"><strong>docs</strong></a>.</p><p>Now that React is available in this file, you can update our JS code to React code. In the <strong>script</strong> tag, you have used <strong>React.createElement</strong> to create the same <strong>h1</strong> element. Similarly, you used the React <strong>createRoot</strong> API to create the root and then render the header in the root.</p><p>Now, the above example is with a simple header; if you have multiple elements in the file, your file will look like the following:</p><pre>&lt;!--Step 4--&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>&lt;script crossorigin src=&quot;https://unpkg.com/react@18/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>&lt;script crossorigin src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>    const heading1 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 1&quot;)<br>    const heading2 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 2&quot;)<br>    const heading3 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 3&quot;)<br><br>    const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;))<br><br>    root.render([heading1, heading2, heading3]);<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Step 4:</strong> Ok, so now we have three headers and this one html file holding a lot of things, so it’s better to move this piece of react code to a separate file.</p><p>App.js</p><pre>const heading1 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 1&quot;)<br>const heading2 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 2&quot;)<br>const heading3 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 3&quot;)<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;))<br><br>root.render([heading1, heading2, heading3]);</pre><p>index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>&lt;script crossorigin src=&quot;https://unpkg.com/react@18/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>&lt;script crossorigin src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;App.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>I hope it’s pretty much clear now.</p><p><strong>Step 5:</strong> Now, in big projects, you cannot use React <strong>CDN links</strong>, as we need one place where all these dependencies can be picked up and used. For this, we will run the below command:</p><pre>npm run init</pre><p>After running this, it will ask for a few basic details about your project, like name, description, etc., which you can provide accordingly.</p><p>Then you can run <strong><em>npm install react</em></strong> and <strong><em>npm install react-dom</em></strong> which will install <strong>react</strong> and <strong>react-dom</strong> libraries in our application in the <strong>package.json</strong> file. Now, you can remove the <strong>CDN links</strong>. Once your <strong>package.json</strong> is generated with <strong>react</strong> and <strong>react-dom</strong>; you can add other commands to your scripts section in the <strong>package.json</strong> file</p><pre>&quot;dev&quot;: &quot;vite dev&quot;,<br>&quot;build&quot;: &quot;vite build&quot;,</pre><p>As we are using <strong>vite </strong>as the build tool, you can add commands to run the application locally(<strong>npm run dev</strong>) and build the application using vite (<strong>npm run build</strong>). Similarly, you also need to create a config file, i.e., <strong>vite.config.js,</strong> for <strong>vite</strong> with basic configuration to have react plugin support.</p><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>    plugins: [react()],<br>}) </pre><p>Now, because there are no <strong>CDN links</strong> available, you need to import React and React DOM in the App.js file to use them, but you need to use <strong>type=”module”</strong> in your script tag in the html file. This step is required so that import will work considering it is a Javascript module.</p><p>App.js</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br><br>const heading1 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 1&quot;)<br>const heading2 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 2&quot;)<br>const heading3 = React.createElement(&quot;h1&quot;, {}, &quot;Heading 3&quot;)<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;))<br><br>root.render([heading1, heading2, heading3]);</pre><p>index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>&lt;script type=&quot;module&quot; src=&quot;App.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Step 6:</strong> Now, you can update your JS file to JSX. <strong>JSX</strong> gives us support for HTML-like syntax, so you can change our JS file to have HTML-like syntax, as shown in the below example.</p><p>Till now, in the previous file, you had 3 heading variables, but now you will be changing these headings to <strong>Header</strong>, <strong>Body, </strong>and <strong>Footer</strong> functional components, like below:</p><p>components/Header.jsx</p><pre>import React from &quot;react&quot;;<br><br>const Header = () =&gt; &lt;h1&gt;Build Create React App using Vite from scratch&lt;/h1&gt;<br><br>export default Header;</pre><p>components/Body.jsx</p><pre>import React from &quot;react&quot;;<br><br>const Body = () =&gt; &lt;p&gt;You have successfully created create-react-app(CRA)/create-react-vite clone :)&lt;/p&gt;<br><br>export default Body;</pre><p>components/Footer.jsx</p><pre>import React from &quot;react&quot;;<br><br>const Footer = () =&gt; &lt;p&gt;© All by your own&lt;/p&gt;<br><br>export default Footer</pre><p>App.jsx</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import Header from &quot;./component/Header&quot;;<br>import Body from &quot;./component/Body&quot;;<br>import Footer from &quot;./component/Footer&quot;;<br><br>const Container = () =&gt; {<br>    return (<br>        &lt;div&gt;<br>            &lt;Header /&gt;<br>            &lt;Body /&gt;<br>            &lt;Footer /&gt;<br>        &lt;/div&gt;<br>    )<br>}<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;))<br><br>root.render(&lt;Container /&gt;);</pre><p>Simple. That’s all you need to create our own version of CRA.</p><p>If you have ever noticed <strong>create-react-app</strong> closely, it gives a build tool — <strong>webpack,</strong> and we used <strong>vite </strong>here — some pre-written scripts that we have written ourselves, the ability to write <strong>JSX</strong> from the start, and also some testing framework and formatting support, which we can also get just by doing npm install.</p><p>My intention to write this blog was not to motivate people to stop using <strong>create-react-app</strong>, but to understand the basics behind what CRA does out of the box for us. It’s good to use some libraries to generate the boilerplate code for us, but not at the cost of forgetting the basics behind it, hope this helps. That’s what I want to share on this blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2319e8af69a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jest ▶ Vitest Migration]]></title>
            <link>https://srivastavaankita080.medium.com/jest-vitest-migration-79f4735dd5d0?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/79f4735dd5d0</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[vee-validate]]></category>
            <category><![CDATA[vitest]]></category>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 18:01:44 GMT</pubDate>
            <atom:updated>2022-11-22T18:01:44.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDjzvCeTpuiFoJ6G0p-bzw.jpeg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0sjAhzv1aSA&amp;psig=AOvVaw3wZ_HO1Hu8iYotq0HAjzH1&amp;ust=1668875804547000&amp;source=images&amp;cd=vfe&amp;ved=0CBEQjhxqFwoTCICKuv-UuPsCFQAAAAAdAAAAABAD">https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0sjAhzv1aSA&amp;psig=AOvVaw3wZ_HO1Hu8iYotq0HAjzH1&amp;ust=1668875804547000&amp;source=images&amp;cd=vfe&amp;ved=0CBEQjhxqFwoTCICKuv-UuPsCFQAAAAAdAAAAABAD</a></figcaption></figure><p>I started with vite migration and found vite performance a lot better compared to vue-cli build and dev server start up time. So, as I already told my vite migration story in my previous blog <a href="https://medium.com/@srivastavaankita080/vue-cli-vite-migration-e1aba37e649d">here</a>, in case anyone is interested in reading that as well, After my vitest migration, when I ran my unit tests, all tests started breaking, which led me to start my vitest migration. So let’s begin with vitest migration.</p><h3>Migration Guide</h3><p><strong>Step 1</strong>: First, you need to install the below dependencies to get started with vitest</p><pre>npm install --save-dev vitest jsdom c8</pre><p>We are installing the below packages:</p><ul><li><strong>Vitest:</strong> As our test runner</li><li><strong>jsdom: </strong>As we don’t have an actual dom in the test, so to have something like actual dom in our tests</li><li><strong>c8/istanbull:</strong> Both comes for coverage report for our unit tests. c8 being the default one i.e.., if you just install c8 and istanbul but don’t tell vitest which one to use for coverage, it will start generating your coverage report using c8.</li></ul><p><strong>Step 2: </strong>Now you must update your vite.config.ts file with test configuration, as shown below:</p><pre>test: {<br>    environment: &#39;jsdom&#39;,<br>    coverage: {<br>      reporter: [&#39;text&#39;, &#39;html&#39;],<br>      exclude: [<br>        &#39;node_modules/&#39;,<br>        &#39;./tests/vitest.setup.ts&#39;,<br>      ],<br>      all: true,<br>      lines: 80,<br>      functions: 80,<br>      branches: 80,<br>      statements: 80,<br>    },<br>    setupFiles: [&#39;./tests/vitest.setup.ts&#39;],<br>    globals: true,<br>  }</pre><p>A few details must be addressed here:</p><ul><li>Similar to the Jest setup file, we will be creating a file for the Vitest setup, and you need to provide the path for that file in <strong>test.setupFiles.</strong></li><li>I have added an environment called “jsdom”; as we do not have an actual DOM, we are using jsdom to mimic browser behavior.</li><li>I have set up my coverage configuration to exclude my node_modules and src/vitest.setup.ts files so that vitest will generate a coverage report excluding them. Also, I have set up a threshold, mentioning that metrics should be at least 80%, otherwise the coverage will fail. All of this is very similar to Jest.</li><li>In Jest, by default, <strong>expect, describe, </strong>etc. used to be present, and that’s why we don’t need to import them explicitly. Vitest does not have these packages available by default, and hence either we need to import them everywhere or we can configure Vitest to make them globally available by setting globals: true.</li><li>One more important point to note, vitest.setup.ts is the file that will have the same configuration that you used to keep with Jest, which can be different in everyone else&#39;s case. Make sure you import this in your vitest setup file: import ‘<a href="http://twitter.com/testing">@testing</a>-library/jest-dom/extend-expect’; otherwise you will get an error - <strong>Error: Invalid Chai property: toHaveTextContent </strong>etc, as this import is responsible for including all such things in our tests. This step is required if you are using testing-library.</li></ul><p><strong>Step 3:</strong> We will now use vitest to replace Jest functions, spy, and stubs. You need to import { vi } from vitest, and then all jest.fn() will become vi.fn().</p><p><strong>Step 4:</strong> After removing Jest from everywhere, we will update our package.json file scripts containing the following:</p><pre>&quot;scripts&quot;: {<br>    &quot;serve&quot;: &quot;vite&quot;,<br>    &quot;serve:prod&quot;: &quot;vite preview&quot;,<br>    &quot;build&quot;: &quot;vite build&quot;,<br>    &quot;test&quot;: &quot;TZ=UTC vitest run&quot;,<br>    &quot;test:coverage&quot;: &quot;TZ=UTC vitest run --coverage&quot;,<br>    &quot;test:watch&quot;: &quot;TZ=UTC vitest&quot;,<br>  },</pre><ul><li>serve: This will spin up your application locally.</li><li>serve:prod: This will serve the application from the local ./dist folder</li><li>build: This will create a production build locally.</li><li>test: For my application, I need timezone to be in UTC so I have to set <strong>TZ=UTC</strong>, If you don’t need that you can simply omit it and it will run all you test with coverage.</li><li>test:coverage: This will run all the tests with coverage.</li><li>test:watch: It will also run all the test but in watch mode.</li></ul><p>Now, you can uninstall @types/jest, @vue/cli-plugin-unit-jest and vue-jest from your package.json devDependencies.</p><p><strong>Step 5:</strong> If you are using typescript in your project, then you need to add vite/client and vitest/global in your tsconfig file like below:</p><pre>&quot;types&quot;: [<br>      &quot;vite/client&quot;,<br>      &quot;vitest/globals&quot;,<br>   ],</pre><p>And Tada! 🎊 You run npm run test and you should be able to see all your tests running perfectly fine 👏.</p><p>But wait, if you’re still having problems and a lot of tests are failing for you, as they did for me, please consider the following::</p><ol><li>This might be very specific to my project, but it might help someone else, so I’m sharing it here. As mentioned in vite migration blog, I had a dynamic component for Icon.vue that was rendering as an HTML tag in tests before migration, but after migration it started coming as <strong>raw svg</strong> code, so to fix it, I replaced the html assertions with snapshot tests.</li><li>Then I have a few tests that were spying on a window object, as shown below:</li></ol><pre>// Before migration<br>windowSpy.mockImplementation(() =&gt; ({ history: { length: 3 }}));</pre><p>After vitest migration, this was not working because of vitest architectural choice, it uses different instances of the window object in test and source code. As a result, we can’t see a window object in the vitest.</p><p>Now for fixing this tests, we need <strong>history.length</strong> to be available so I used <strong>stubGlobal </strong>provided by vitest.</p><pre>vi.stubGlobal(&#39;history&#39;, { length: 2, go: vi.fn() })</pre><p>vitest <strong>stubGlobal</strong> will put the variable in global scope, now whenever <strong>history.go()</strong> or <strong>history.length</strong> will be called, this stub will be used.</p><p>3. ) I was having lot of tests dependent on timezone as well. In Jest, we are able to set up timezone before tests starts up, in <strong>process.env</strong>. But I searched a lot in vitest to set the timezone in environment variable, the only way I could figure out is by running the command TZ=UTC vitest run which will set my timezone to UTC before running the tests.</p><p>Now this works fine for terminal, but what if I want to run a single file from IDE which does not use this command from package.json file. I searched for few plugins to check if I can get vitest support in IDE( I was using IntelliJ) so that I can set environment variable for all my tests. I found that IntelliJ latest version(2022.3, still in beta) have vitest support, but with this also you can set up environment variable just for a single file 😕. That means whenever you are running any new file, you need to go and set the environment variable using Edit configuration setting.</p><blockquote><strong>Note:</strong> As IntelliJ latest version was in beta, I used Jetbrains toolbox to keep it separate with my existing IDE setup. So I am not suggesting you to remove your existing version or IDE, still you can have latest version of IDE, which definitely have more verbose errors when vitest test fails and better support for vitest.</blockquote><p>4.) Another point I emphasized in my vite migration blog as well was checking for conflicting versions in package.json. For my project, I was using the <strong>vee-validate</strong> library for validations, and because there was an issue with the previous versions of this library and it was not compatible with vite, it started giving wrong data, which failed a lot of tests for me. I am adding my package.json version below so that in case you end up with this issue, you know the library versions that at least worked for me:</p><pre>&quot;dependencies&quot;: {<br>    &quot;@apollo/client&quot;: &quot;^3.7.1&quot;,<br>    &quot;@vue/apollo-composable&quot;: &quot;4.0.0-alpha.19&quot;,<br>    &quot;@vitejs/plugin-vue&quot;: &quot;3.2.0&quot;,<br>    &quot;eslint-import-resolver-typescript&quot;: &quot;^3.5.2&quot;,<br>    &quot;graphql&quot;: &quot;^16.5.0&quot;,<br>    &quot;vee-validate&quot;: &quot;4.5.11&quot;,<br>    &quot;vite&quot;: &quot;^3.0.0&quot;,<br>    &quot;vue&quot;: &quot;3.2.33&quot;,<br>    &quot;vue-router&quot;: &quot;4.0.14&quot;,<br>  },</pre><p>Also, try to avoid using ^ or ~ where there are strict versions given in the above JSON file, this literally ate a lot of my time fixing it.</p><p>If you are taking care of these points and have followed all the steps in this blog, you should be able to run all your tests perfectly fine. But, if you are still facing any problems or need any help with migration, please feel free to leave a comment. That’s all I want to share, and I hope it will be helpful to someone who is trying to migrate to vitest from jest. Also, if you have any feedback for the blog, feel free to leave a comment 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79f4735dd5d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue-cli ▶ Vite Migration]]></title>
            <link>https://srivastavaankita080.medium.com/vue-cli-vite-migration-e1aba37e649d?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1aba37e649d</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 17:51:53 GMT</pubDate>
            <atom:updated>2022-11-22T18:59:41.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1_cmAtWuAguHLz5SEFrW4g.jpeg" /><figcaption><a href="https://www.google.com/search?q=vue-cli+to+vite+migration&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=2ahUKEwjW1bqdvML7AhWGu6QKHXf5Ab8Q_AUoA3oECAIQBQ&amp;biw=1787&amp;bih=917&amp;dpr=2#imgrc=YFJPUyoLf-J76M">https://www.google.com/search?q=vue-cli+to+vite+migration&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=2ahUKEwjW1bqdvML7AhWGu6QKHXf5Ab8Q_AUoA3oECAIQBQ&amp;biw=1787&amp;bih=917&amp;dpr=2#imgrc=YFJPUyoLf-J76M</a></figcaption></figure><p>Yes, this is yet another blog that will tell you about how to migrate vue-cli and webpack to vite, but with a few additional steps. Despite the fact that there are so many blogs available for vite migration, I decided to write this blog because of the challenges I faced while migrating my application to vite. However, if you have a basic Vue application, you can easily follow this blog. My application had a bit different setup than a basic Vue application, which we will be seeing here.</p><h3>Tech Stack</h3><p>My current project was built using the Create Vue app, so some of the obvious dependencies like vue-cli, webpack, babel, jest, etc. were already there. Other than this, below are the mentioned technologies:</p><ul><li>Vue3 with Testing Library for Frontend Development</li><li><a href="https://www.npmjs.com/package/graphql">GraphQL</a> for BFF</li><li><a href="https://www.npmjs.com/package/@vue/apollo-composable">Vue Apollo Composable</a></li><li><a href="https://www.npmjs.com/package/@apollo/client">Apollo Client</a></li><li><a href="https://www.npmjs.com/package/vee-validate">Vee-validate</a> for validations</li><li>Typescript</li></ul><h3>Migration Guide</h3><p>When I started following other blogs/documentation for migration, I faced a few challenges as I was also using graphQL and the Apollo client in the project. Other than this, I have a few challenges, which we will resolve here. For the time being, let us begin migration:</p><p><strong>Step 1:</strong> The first step is to remove any vue-cli dependencies present in your package.json file.</p><pre>//remove below dependencies<br>&quot;@vue/cli-plugin-babel&quot;: &quot;&lt;any version&gt;&quot;,<br>&quot;@vue/cli-plugin-eslint&quot;: &quot;&lt;any version&gt;&quot;,<br>&quot;@vue/cli-plugin-router&quot;: &quot;&lt;any version&gt;&quot;,<br>&quot;@vue/cli-plugin-vuex&quot;: &quot;&lt;any version&gt;&quot;, <br>&quot;@vue/cli-service&quot;: &quot;&lt;any version&gt;&quot;, </pre><p><strong>Step 2:</strong> Now, you need to introduce vite in your application by running the below command, which will install vite and the vite vue plugin to your package.json file.</p><pre>npm install vite @vitejs/plugin-vue</pre><p>Also, if you’re using Vue2, you should probably install one more dependency, which I skipped because I was using Vue3 This is only required for projects getting migrated from Vue2 ▶️ vite.</p><pre>npm install vite-plugin-vue2</pre><p><strong>Step 3:</strong> Now that you have vite in your application, you can remove the below-mentioned dependency, as it will be taken care of by the vite plugins.</p><pre>&quot;vue-template-compiler&quot;: &quot;&lt;any version&gt;&quot;   //remove it</pre><p><strong>Step 4: </strong>After installing vite, we must remove any unnecessary dependencies and files<strong>. </strong>We don’t need the <strong>babel.config.js</strong> file anymore, so we can delete it. As we don’t need Babel, we will remove the dependencies associated with it and uninstall it as well.</p><pre>&quot;babel-eslint&quot;: &quot;&lt;any version&gt;&quot;,   //remove it<br>&quot;core-js&quot;: &quot;&lt;any version&quot;,         //remove it</pre><p><strong>Step 5:</strong> Now, we will configure vite in our application. To accomplish this, we will create a new file, <strong>vite.config.js</strong> as shown below:</p><pre>import { defineConfig } from &#39;vite&#39;;<br>import vue from &#39;@vitejs/plugin-vue&#39;;<br>import { fileURLToPath } from &#39;url&#39;;<br>import path from &#39;path&#39;;<br><br>const filename = fileURLToPath(import.meta.url);<br>const pathSegments = path.dirname(filename);<br><br>export default defineConfig({<br>  plugins: [vue()],<br>  resolve: {<br>    alias: {<br>      &#39;@&#39;: path.resolve(pathSegments, &#39;./src&#39;),<br>    },<br>    extensions: [&#39;.mjs&#39;, &#39;.js&#39;, &#39;.ts&#39;, &#39;.jsx&#39;, &#39;.tsx&#39;, &#39;.json&#39;],<br>  }<br>})</pre><p>This is the basic configuration of the vite config file with a few additional configurations for my project, which I will explain so that you can decide whether to keep it or not for your use case.</p><ul><li><strong>resolve.alias:</strong> I added this config just for a relatively smaller path when I am importing any file into the project. A file that is present at path ./src<strong>/folder1/file1</strong> can be imported using <strong>@/folder1/file1</strong>.</li><li><strong>resolve.extensions:</strong> As mentioned before, I am also using typescript in the project, so I added support for a few extensions.</li></ul><p>Now, because I am using GraphQL and the Apollo client, just having the above vite configuration gave me an error mentioning that <strong><em>it could not find React,</em></strong> and I was wondering why even it was looking for React in a Vue application. After doing some research, I found that Apollo Client was internally creating this issue. So, to fix this error, we need to add the below code to our vite config file. This step you might not find in the other vite migration blogs as it’s very specific to the Apollo client, which others might not be using.</p><pre>optimizeDeps: {<br>    include: [&#39;@apollo/client/core&#39;, &quot;@vue/apollo-composable&quot;,],<br>    exclude: [&#39;@apollo/client&#39;],<br>  }</pre><p><strong>Step 6:</strong> Before Vite, your index.html file used to get served from public folder but not anymore. Vite looks for your index.html file in your root directory. So, <strong>move your </strong>index.html<strong> file outside public folder</strong> for vite to found it. And yes leave your favicon’s and other files there only, no need to move them.</p><p><strong>Step 7:</strong> Few more changes required in index.html.</p><p>a.) Firstly, We need to remove <strong>&lt;%= htmlWebpackPlugin.options.title %&gt;</strong> from your title tag or anywhere else in your index.html file and replace it with hardcoded String</p><pre>&lt;title&gt;&lt;%= htmlWebpackPlugin.options.title %&gt;&lt;title&gt; //Delete it<br>&lt;title&gt;My Project Title&lt;title&gt; //Add this</pre><p>b.) Next, we need to remove <strong>&lt;%= BASE_URL%&gt;</strong> from your link tag and replace it with the actual path, as shown below:</p><pre>&lt;link rel=&quot;icon&quot; href=&quot;&lt;%= BASE_URL %&gt;/favicon.ico&quot;&gt; //Delete it<br>&lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot;&gt; //Add the hard coded path for favicon </pre><p>c.) Then, you also need to inject your Javascript application manually, because it’s no longer getting auto injected. For injecting Javascript, add this to your index.html file, where <strong>/src/main.ts</strong> is the main file to start the application.</p><pre>&lt;script type=&quot;module&quot; src=&quot;/src/main.ts&quot;&gt;&lt;/script&gt;</pre><p><strong>Step 8:</strong> Now, we will update the environment variable in the application. All the environment variables starting with <strong>VUE_APP_XXX</strong> will be renamed to <strong>VITE_APP_XXX</strong> for Vite to understand them.</p><p>Also, prior to vite migration, we used process.env.VUE_APP_XXX to access environment variables, but we will now replace this with import.meta.env.VITE_APP_XXX throughout the project. You should be able to access all the environment variables using <strong>import.meta.env</strong> in the application.</p><p><strong>Step 9: Now, wherever we are importing vue components, we must include the.vue extension. </strong>This is an important step for SFC imports, but I felt it too much and hence escaped by adding <strong>.vue</strong> extension in the extension list in the<strong> vite.config file</strong>. But let me inform you that this is NOT recommended. So, please go ahead and add the <strong>.vue </strong>extension in your <strong>vite.config.file</strong> for SFC imports.</p><p><strong>Step 10: </strong>Finally, Webpack provided us with a lot of commented code that was essentially used to build applications in chunks, but that no longer works with Vite, so we can remove all such comments<strong>. </strong>Vite also has some support for building applications in chunks, which we can discuss some other time, if people are interested.</p><p>And yes, the migration is complete, so now ideally, my application should be up and running perfectly fine, but when I tried running it, I found all the icons for my project had disappeared, and also, a lot of functionalities were not rendering. Now the real struggle starts, which took a few days for me to get it resolved.</p><p>Let&#39;s discuss those problems:</p><p><strong>Problem 1: No icons/images are getting displayed for me.</strong></p><p>A bit of context here: I have a custom component Icon.vue that uses a vue dynamic component, and we used to pass a prop that is the icon or svg filename, and based on that, it renders the svg file as a vue component. We have an index.ts file that exports all the svg files (around 150 in count) and then gets served by the Icon component.</p><p>Index.ts ( exporting 150 svg files)</p><pre>export { default as image1 } from &#39;./image1.svg&#39;;<br>export { default as image2 } from &#39;./image2.svg&#39;;<br>export { default as image3 } from &#39;./image3.svg&#39;;<br>.<br>.<br>.<br>export { default as image150 } from &#39;./image150.svg&#39;;</pre><p>Icon.vue</p><pre>&lt;template&gt;<br>  &lt;span&gt;<br>    &lt;component :is=&quot;variant&quot; /&gt;<br>  &lt;/span&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot;&gt;<br>import { defineComponent } from &#39;vue&#39;;<br>import * as icons from &#39;@/icons&#39;;<br><br>export default defineComponent({<br>  components: icons,<br>  props: {<br>    variant: {<br>      type: String,<br>      required: true,<br>    },<br>  },<br>});</pre><p>AnyComponent.vue ( usage of Icon component )</p><pre>&lt;Icon variant=&quot;image2/&gt;</pre><p>Previously, my svg files were rendered in this manner, but they have all vanished.</p><p><strong>Solution: </strong>After debugging, I discovered that after vite migration, I was unable to export multiple svg files from index.ts, so I spent a lot of time researching how to export it in vite<strong>. </strong>Vite provides a <strong>glob method</strong> to do the same job, <strong><em>which allows us to import multiple modules from the file system</em></strong>. By providing options, you can choose whether to import it as a svg file or a component. I tried the component way, but it didn’t work for me, so I went ahead with the raw svg format. Also, by default, the glob method does lazy loading of the files, but in my case, I want all the files at once, so I used the <strong>globEager method</strong>. Now, my index.ts got changed and looked like this:</p><pre>const svgModules = import.meta.globEager(&#39;./*.svg&#39;, { as: &#39;raw&#39; });<br>const formattedSvgModules: { [key: string]: unknown } = {};<br><br>Object.keys(svgModules).forEach((filePath) =&gt; {<br>  const svg = svgModules[filePath];<br>  const filename = filePath.replace(&#39;.svg&#39;, &#39;&#39;).replace(/[^(A-Za-z0-9)]/gi, &#39;&#39;).toLowerCase();<br>  formattedSvgModules[filename] = svg;<br>});<br><br>export default formattedSvgModules;</pre><p>I just did a little formatting to get a better <strong>key: value</strong> pair in my object, so you can ignore that if you are fine with objects in this format 😜 :</p><pre>// Before formatting<br>{&#39;./image1-abc.svg&#39;: &#39;&lt;svg&gt;Actual svg code&lt;/svg&gt;&#39; }<br><br>// After formatting<br>{&#39;image1abc&#39;: &#39;&lt;svg&gt;Actual svg code&lt;/svg&gt;&#39; }</pre><p>Also, I changed my Icon component from a dynamic component to a basic span tag with v-html:</p><pre>&lt;template&gt;<br>  &lt;span v-html=&quot;getIcon(variant)&quot;/&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot;&gt;<br>import { defineComponent } from &#39;vue&#39;;<br>import * as icons from &#39;@/icons&#39;;<br><br>export default defineComponent({<br>  props: {<br>    variant: {<br>      type: String,<br>      required: true,<br>    },<br>  },<br>  methods: {<br>    getIcon: (variant: String)=&gt; {<br>      return icons.default[variant.toLowerCase() as keyof Object]<br>    }<br>  }<br>});</pre><p>Cool, this resolves the first problem, and I was able to see all the images rendering in the application.</p><p><strong>Problem 2: </strong>I also discovered that a few functionalities in my application were not rendering; while this was a very project-specific issue, I thought I’d share it in the hope that it can help someone else<strong>. </strong>In my project, we have a lot of permissions, and based on that, we render a few features. Now, we used to get these permissions from the BFF layer, and I was getting all of them from my BFF, but in a few places in my vue app, I was getting undefined for those permissions.</p><p><strong>Solution:</strong> And again, after trying all possible things, I figured out that this issue was specific to a version conflict in the package-lock.json file. The <strong>version clash involved vue3, apollo client, and apollo-composable with vite</strong>. So instead of using different ranges for versions, I started hardcoding specific versions. I’m sharing the versions that helped me so that if anyone has any strange issues after vite migration, they can try the versions that worked for me:</p><pre>&quot;dependencies&quot;: {<br>    &quot;@apollo/client&quot;: &quot;^3.7.1&quot;,<br>    &quot;@vitejs/plugin-vue&quot;: &quot;3.2.0&quot;,<br>    &quot;@vue/apollo-composable&quot;: &quot;4.0.0-alpha.19&quot;,<br>    &quot;graphql&quot;: &quot;^16.5.0&quot;,<br>    &quot;vee-validate&quot;: &quot;4.5.11&quot;,<br>    &quot;vite&quot;: &quot;^3.0.0&quot;,<br>    &quot;vue&quot;: &quot;3.2.33&quot;<br>  }</pre><p>Tada!! I was overjoyed when the vite migration was completed and my application was up and running with all of its features and images. I’d also like to share the metrics that I collected following vitelline migration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13e5h6Mbbozy2qjbOIBi5A.png" /></figure><p>But as far as I know 😕</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkBqbCNNeLWI0Y73NGt%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkBqbCNNeLWI0Y73NGt%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FkBqbCNNeLWI0Y73NGt%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/71d664d04ad821e5403cfac6f73706ec/href">https://medium.com/media/71d664d04ad821e5403cfac6f73706ec/href</a></iframe><p>With all of this excitement, I began running my tests and discovered that they were all failing because we had removed the babel-related files, and Jest requires babel to run the tests:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdBsUACbhvDROt9pbFO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FdBsUACbhvDROt9pbFO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FdBsUACbhvDROt9pbFO%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6aeddc21142c8b8c99fa228f81a45a/href">https://medium.com/media/fa6aeddc21142c8b8c99fa228f81a45a/href</a></iframe><p>Then I realized that there are ways to keep Jest with vite but with other dependencies like esbuild, etc., and that’s when I decided that if I had to put effort into something, I should put effort into Jest to Vitest migration rather than keeping Jest 🙌.</p><p>Thats all I want to share for vite migration, and I hope it will help a lot of people who have not yet moved to vite just because of some blockers. I personally believe the vite community is doing really well, and we have seen the metrics showing how fast it spins and builds up application. If you liked this vite migration journey of mine and are also interested in knowing my <strong>Jest ▶️ vitest migration</strong> story, you can find it <a href="https://medium.com/@srivastavaankita080/jest-vitest-migration-79f4735dd5d0">here</a>. In case you are in the process of vite migration and have some questions or need any help, feel free to drop a comment, I am happy to help 😊. And feedback is always welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1aba37e649d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue Js v-model to the rescue…]]></title>
            <link>https://srivastavaankita080.medium.com/vue-js-v-model-to-the-rescue-50b41789c01d?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/50b41789c01d</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 15:45:22 GMT</pubDate>
            <atom:updated>2022-06-13T15:45:22.837Z</atom:updated>
            <content:encoded><![CDATA[<p>I come from a React Js background with around 3 years of experience. When I start learning Vue Js, a few concepts seems confusing to me. It took some time to get used to these concepts, v-model was one of them. v-model does a lot of things out of the box for us. Let&#39;s deep dive into v-model to understand how beautiful it is 😇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQUENDfi6DEMLzQ0CKt%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQUENDfi6DEMLzQ0CKt%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMTc4eDFxeWh3ZnM3M3U1NXU0MGgxNXg3Y3dqOGN6bGh2aWpmYm1sYSZlcD12MV9naWZzX2dpZklkJmN0PWc%2FQUENDfi6DEMLzQ0CKt%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="324" frameborder="0" scrolling="no"><a href="https://medium.com/media/199d0a58a9bd33474425ca217f6a5fbc/href">https://medium.com/media/199d0a58a9bd33474425ca217f6a5fbc/href</a></iframe><h4>What is a v-model?</h4><p>In general, when we write react component, let’s say which has some input element, we used to have a state for holding the input data and then we used to trigger a method on input event. Now, if I write something similar in Vue, it will look like this:</p><pre>&lt;input<br>  :value=&quot;message&quot;<br>  @input=&quot;(event) =&gt; message = event.target.value&quot;&gt;</pre><p>That means, we are triggering input here manually and then setting the state (message) which again gets assigned to your input element using <strong>value</strong> attribute.</p><p>Now in vueJs, v-model says let me take this responsibility from you and help you with the manual update part. That means, we just need to have a state/data, and assigned it to the v-model, the event(input for input element) triggering part will be taken care of by the v-model and our code will look like this:</p><pre>&lt;input v-model=&quot;message&quot;&gt;</pre><p>V-model does two-way binding for us i.e., if input changes the data(<strong>message</strong>) will update or if data changes it updates the input. Pretty simple isn’t it!!</p><p><strong>Note: v-model will take the control for triggering the event and which event will get triggered, this based on the element which is getting used</strong>. e.g.,</p><p>For &lt;input&gt; with text type, it triggers @input event and use value property, for &lt;input type=&quot;checkbox&quot;&gt; or &lt;input type=&quot;radio&quot;&gt; it triggers @change event and usechecked property, for &lt;select&gt; it triggers @change event and usevalue property.</p><blockquote><strong>Note:</strong> All these event listening works well for native tag like input, select etc. but for custom vue element, v-model works differently where you need to explicitly emit the event with the updated value and v-model does the job of listening the updated value and changing it.</blockquote><p>Honestly, you will find all these things in the Vue documentation but there is one use case that I want to share that took sometime to understand initially being new to VueJs. Let’s discuss this and also explore v-model behaviour for vue custom element.</p><h4><strong>The use case for v-model</strong></h4><p><strong>Scenario:</strong> We have 1 parent component, which has 3 child components let&#39;s say child1, child2, and child3. We will be selecting some data in each child component and finally, at child3, we will do a submission where all the data get submitted. You can consider it like, we are building a form where you have 3 pages and finally we submit all the selected data on the third page.</p><pre>Parent.vue<br>  Child1.vue<br>  Child2.vue<br>  Child3.vue</pre><p>We thought of 2 approaches to solve this use case:</p><p><strong>Approach 1:</strong> Coming from React background, Initially, our team thought that we will create a Parent component that will hold all the data, methods and submission logic in the parent component itself, as parents should be aware of all the child data. We will pass all the data as prop and function as a reference to the child component and trigger the function from the child whenever required.</p><p><strong>Problem with Approach 1:</strong> In this approach, there is one problem. In the child1 component, we have two dropdowns that are interrelated i.e., when you select the first dropdown value, the second dropdown options will get changed accordingly. We have created a method for doing the parsing which looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9afe815f523fe34370e5ecd9b2c7ebc/href">https://medium.com/media/a9afe815f523fe34370e5ecd9b2c7ebc/href</a></iframe><p>Now the problem was where to keep this method, in Child1 or in the parent. The data this.secondDropdownValue was data in Parent and prop in child1 component, so we cannot keep this method in child1 as we cannot update/change prop. Now, we are forced to keep this method in the parent component along with the dropdown options data in the parent.</p><p>When we decided to keep it in the parent component, we realised that this method&#39;s responsibility should be with the child and not with the parent because parent should not deal with parsing/clearing any child data and this way we landed on approach 2.</p><p><strong>Approach2:</strong> Now, we were thinking that we should maintain data in each child component so that all such methods as parsing responsibility will be along with the correct owner which was child1 in the previous case.</p><p>Now when we want to do the final submission where we need all data, we again face challenges because in child3, as we need child1 and child2 data and siblings should not share data as per recommendations. This made us realise that no matter what, we need to maintain all the child data at the parent level so that during final submission you can reach out to the parent and get all your data i.e., data at both parent and child. Basically, we were maintaining data in child, and then on any event(e.g., input, change) trigger, we do emit a custom event from child component and then we will explicitly ask parent to listen that event and update the data manually.</p><p><strong>Problem with Approach 2: </strong>In approach 2, though we have solved the problem of moving the parsing method to the child1 component and everything else is working fine, we might end up in a situation of data inconsistency. As we are maintaining data at 2 places, child as well as parent, If we forget to update data at one place then we end up seeing inconsistent data in our UI, because parent and child will be having different data now.</p><p>Now, both approaches have some or the other problems. we were looking for some other solution as this was the very likely occurring scenario, and then the v-model comes to rescue. Let&#39;s discuss how we solved this issue:</p><p>We kept all our data at the parent component and passed it as a prop to the child component. Parent data will always be single source of truth to avoid inconsistency. Now the parent and child component will get updated like below:</p><p>Parent.vue</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebda7651bc117aabb0fa025acf6b52a1/href">https://medium.com/media/ebda7651bc117aabb0fa025acf6b52a1/href</a></iframe><p>Child1.vue</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0198a16b735e2f0d7578a269b123e741/href">https://medium.com/media/0198a16b735e2f0d7578a269b123e741/href</a></iframe><p>Now here in the updated child1 component, you can see updateFirstDropdownValueAndLoadSecondDropdownOptions method which does the job of updating <strong>firstDropdownValue, </strong>which is prop in updated child1 component. If you check updateModelValue(event, type) method, we explicitly triggered event <strong>update:firstDropdownValue</strong> or <strong>update:secondDropdownValue </strong>based on the type we are triggering for, so that v-model in Parent component will listen to it automatically.</p><blockquote><strong>Note:</strong> <strong>update:firstDropdownValue </strong>trigger will update <strong>firstDropdownValue </strong>data in the parent component as v-model will listen it automatically for firstDropdownValue, and same goes for the <strong>update:secondDropdownValue.</strong></blockquote><p>This method updateModelValue(event, type) gets executed using a listener <strong>@update: model-value </strong>in the dropdown component. Now, you can assume dropdownContainer as a custom component which has a title and a dropdown.</p><blockquote><strong>Note:</strong> We did explicit event listening using <strong>@update: model-value </strong>in the Child1<strong> </strong>component for dropdown, because here we introduced two level of nesting which is <strong>Parent -&gt; Child1 -&gt; DropdownContainer</strong>. As Child1 cannot use v-model on the prop(firstDropdownValue, secondDropdownValue), it cannot listen the event updates automatically like v-model and hence explicit event listening was required. This explicit event listening is not required if it was one level of nesting i.e., Parent -&gt; Child1 where child1 update will be automatically listened by parent v-model.</blockquote><p>if you see loadSecondDropdownOptions method, you will see the first line which is emitting an event with an empty value. This is possible because the v-model at parent will listen, and the update event for <strong>secondDropdownValue</strong> data (present at the parent component) will update the data at the parent level. This way we update the parent without the need of duplicate data at the child and without creating a custom event and explicitly listening it at parent to update it. We do emitted multiple <strong>@update </strong>event but there is no custom event present anymore and v-model also listen the update event automatically without any explicit listening of event at parent level.</p><p>Everything is in sync now without the need for maintaining data in 2 places. This way v-model solves the problem that we faced in both approaches.</p><p><strong>Note:</strong> v-model can be very useful in such cases when you don’t want to manage the update manually for 1 or 2 level of nesting. Incase, you have multiple level of nesting then we end up emitting multiple update event and it will become difficult to track the event.</p><h4>Things you can do with v-model!</h4><ul><li>When you are using <strong>v-model</strong> in a custom component without explicit name, then in the child component, by default v-model gives a prop called <strong>modelValue, </strong>which can be used for reading the value of the passed prop. Let&#39;s see here, how it looks:</li></ul><p>Parent component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3caa4ba2b38d716671610a1e6fbbc6c1/href">https://medium.com/media/3caa4ba2b38d716671610a1e6fbbc6c1/href</a></iframe><p>In the above code, we are passing fruits data as a prop to the Child custom component.</p><p>Child component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dafa7fe2f40e4b99cdb8f464fb87ac90/href">https://medium.com/media/dafa7fe2f40e4b99cdb8f464fb87ac90/href</a></iframe><p>In the child component, you get <strong>modelValue</strong> as a prop which can be used for various purposes.</p><p><strong>Note</strong>: Let’s say we end up in the same scenario which we discussed earlier and because of this <strong>modelValue</strong> prop, now we will be updating the parent data by emitting events like this.$emit(&#39;update:modelValue&#39;, value) . As we did not provide specific names to v-model, it will pick up the default one which is <strong>modelValue</strong>.</p><ul><li>v-model provides different modifiers which can be used as per the use case. For example :<br> — <strong>v-model.lazy</strong>: This modifier will sync your input with the data after the change event instead of on every input event.<br> — <strong>v-model.number:</strong> This modifier will typecast the user input to a number, works very similar to type=number.<br> — <strong>v-model.trim:</strong> This modifier will trim the extra whitespaces from the user input.</li><li>You can also create custom modifiers, which you can access from props via this.modelModifiers.modifierName but in case you have given a name to v-model like <strong>v-model: first,</strong> then you need to access this.firstModifiers.modifierName.</li></ul><p>This is all I want to share as my learning for v-model with the forum. Hope it will help you in some way. Please provide your valuable feedback 🙂.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50b41789c01d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VueJs COMPUTED & WATCHERS Explained!!]]></title>
            <link>https://srivastavaankita080.medium.com/vuejs-computed-watchers-explained-7b6416ebfa18?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6416ebfa18</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-engineering]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Wed, 11 May 2022 16:41:05 GMT</pubDate>
            <atom:updated>2022-05-11T16:41:05.928Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started working with Vue Js a few months back, the most confusing thing I felt, is to decide when to use computed property and when to use watchers. Most of the time I ran into a situation where I end up writing a watcher, though a watcher was not required there. I used to be very confused thinking of these two and that&#39;s the reason I want to pen down my learnings.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdCdjSBHCwQQGBXayHM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FdCdjSBHCwQQGBXayHM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FdCdjSBHCwQQGBXayHM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/92ae5be5ad9e9b7a5b2023205611eba2/href">https://medium.com/media/92ae5be5ad9e9b7a5b2023205611eba2/href</a></iframe><p>Let’s start understanding what is the difference between computed properties and watchers.</p><h3>Computed Property</h3><h4><strong>What is computed property?</strong></h4><p>Computed property enables us to perform any computation with existing data and composes new data with the computed result. In simple terms, you can consider it as a pure function that also creates data for you, so that you can use the computed value wherever required. More practical, less theory. Let’s see an example:</p><pre>&lt;template&gt;<br>  &lt;div&gt;{{foo}}&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;</pre><pre>export default {<br>  components: { EvenOdd },<br>  data() {<br>    return {<br>      bar: 100<br>    }<br>  },<br>  computed: {<br>    foo() {<br>      return (this.bar % 2 === 0) ? &#39;even&#39; : &#39;odd&#39;<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><pre>Output: even</pre><p>In the above example, We used the <strong>bar</strong> data field to compute the value for the <strong>foo</strong> computed property. Every time whenever there is a change in the <strong>bar</strong> data field, the computed property will get executed and update the value for <strong>foo</strong>. Now, we are able to use <strong>foo</strong> in the template expression because the computed property creates a data field with the same name and then performs the computation on every change of <strong>bar</strong> data field, which updates the <strong>foo</strong> value.</p><h4>Is Computed property always pure functions?</h4><p>As shown in the above example, the computed property is a <a href="https://www.geeksforgeeks.org/pure-functions-in-javascript/">pure function</a>, but what if I want to update any data field value inside the computed property?</p><p>In most cases, you will not end in a situation where you need to set some data in computed property and that’s why computed properties by default are getters only. For some rare scenarios, we can write a setter like this to update the data value:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;div&gt;Employee Details&lt;/div&gt;<br>    &lt;div&gt;{{details}}&lt;/div&gt;<br>    &lt;button @click=&quot;changeEmployeeDetails&quot;&gt;Change Details&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  name: &#39;Employee&#39;,<br>  data() {<br>    return {<br>      employee: {<br>        name: &#39;John&#39;,<br>        type: &#39;permanent&#39;<br>      }<br>    }<br>  },<br>  methods: {<br>    changeEmployeeDetails() {<br>      this.details = &#39;Tom: Contract&#39;<br>    }<br>  },<br>  computed: {<br>    details: {<br>      get() {<br>        return `${this.employee.name}: ${this.employee.type}`<br>      },<br>      set(value) {<br>        const employeeDetails = value.split(&#39;: &#39;)<br>        this.employee.name = employeeDetails[0]<br>        this.employee.type = employeeDetails[1]<br>      }<br>    }<br>  }<br>}</pre><p>As you can see in the above example, we have a setter that gets a value as a parameter and set it back to the employee data field. This setter will get called only when you try to change computed property generated data field value(<strong>details </strong>in our case), which we are doing on button clickChange Name.</p><h4>Best practices</h4><ul><li>Computed property getters should always be pure functions.</li><li>Try to avoid mutating computed property as much as possible. Instead of mutating the computed property, you should try to update the data field which triggers new computations and invokes the getter. e.g., In the above example, we changed <strong>details</strong>(computed property) directly in the method invocation, Instead of that, we could have changed the <strong>employee</strong> object which would have triggered new computation, and updated the <strong>details </strong>computed property<strong>.</strong></li></ul><h4>How computed property is different from methods?</h4><p>This is important to understand that <strong>computed properties</strong> and <strong>methods</strong> have a different purpose to serve. In a nutshell:</p><p>The <strong>computed property</strong> will always give the same value for the same data field value(<strong>pure functions</strong>) and will get invoked only when the data field value gets updated.</p><p><strong>Methods</strong> need not be <strong>pure functions</strong> and can be invoked any number of times. They do not create data fields for us.</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;button @click=&quot;nowMethod&quot;&gt;Display Timestamp&lt;/button&gt;<br>    &lt;div&gt;MethodInvocation: {{this.timestamp}}&lt;/div&gt;<br>    &lt;div&gt;ComputedProperty: {{now}}&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  name: &#39;Time&#39;,<br>  data() {<br>    return {<br>      timestamp: &#39;&#39;<br>    }<br>  },<br>  methods: {<br>    nowMethod() {<br>      this.methodTime = <em>Date</em>.now()<br>    }<br>  },<br>  computed: {<br>    now() {<br>      return <em>Date</em>.now()<br>    }<br>  }<br>}</pre><p>Here, every time you click the button Display Timestamp you will see the method invocation happening and the value is getting changed, but the computed property will never get changed because here computed property does not have any reactive dependency (any mutation to data) which triggers it.</p><p>The computed property also does cache of data while the method does not and thus every method invocation, re-renders the DOM tree. The computed property will re-render only if the dependent data gets mutated.</p><h3>Watchers</h3><h4>What are watchers?</h4><p><strong>Watchers</strong> enable us to monitor or spy on a data field value and perform a set of operations when the data field values changes.</p><p>We should always try to have computed properties as a pure function, and avoid any mutations. But in rare cases, when we have to perform side-effects e.g., mutations in DOM tree or any other state changes, <strong>watchers</strong> comes to the rescue.</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>  &lt;div&gt;<br>    &lt;span&gt;Celsius:&lt;/span&gt;<br>    &lt;input v-model=&quot;celsius&quot;/&gt;<br>    &lt;div&gt;{{this.celsius}}&lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div&gt;<br>    &lt;span&gt;fahrenheit:&lt;/span&gt;<br>    &lt;input v-model=&quot;fahrenheit&quot;/&gt;<br>    &lt;div&gt;{{this.fahrenheit}}&lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  name: &#39;Temperature&#39;,<br>  data() {<br>    return {<br>      celsius: 0,<br>      fahrenheit: 32<br>    }<br>  },<br>  watch: {<br>    celsius(newValue, oldValue) {<br>      this.fahrenheit = ((newValue * (9/5)) + 32)<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><p>Here, in the above example, we put a watcher on the celsius data field and when we will update the celsius data field in the input, the watcher will perform the execution and update the Fahrenheit value depending on the changed celsius value. If you feel v-model is something new here, you can consider it as a value attribute for the input tag.</p><p>Some important points:</p><ul><li>The name for the watcher should be the same as the data field which you want to spy on, and thus you can watch one data field at a time.</li><li>Watcher takes 2 arguments <strong>newValue</strong> and <strong>oldValue</strong> based on which you can perform a set of actions.</li></ul><h4>Configuration in watchers</h4><p>There are different configurations available for watchers as below:</p><ul><li>deep: Watchers can be very helpful in mutation, but by default, watchers do not mutate nested properties and if we want to mutate the nested property we need to set deep: true in the watcher as below:</li></ul><pre>watch: {<br>    someMethod: {<br>      handler(newValue, oldValue) {<br>        .....<br>      },<br>      deep: true<br>  }<br>}</pre><ul><li>flush: When any data field value gets updated then, the DOM tree gets re-render and the watcher callback also gets executed. By default, the order of execution of these events is in a reverse way i.e., the watcher callback will get executed first and then the DOM tree gets re-render. If incase we are accessing the DOM tree inside the watcher callback, we will get an outdated DOM tree. In such a scenario, we can set flush: &#39;post&#39; which will help us to get the updated DOM tree in the watcher callback.</li></ul><pre>watch: {<br>  celsius: {<br>    handler(newValue, oldValue) {<br>      <em>console</em>.log(<em>document</em>.body.innerHTML);<br>      this.fahrenheit = ((newValue * (9/5)) + 32)<br>    },<br>    flush: &#39;post&#39;<br>  },<br>}</pre><p>In the above temperature example, if we have a watcher on celsius which is accessing the DOM tree in the watcher callback without flush: &#39;post&#39; then we will be below output:</p><pre>&lt;div id=&quot;app&quot; data-v-app=&quot;&quot;&gt;<br> &lt;div&gt;&lt;div&gt;<br>  &lt;span&gt;Celsius:&lt;/span&gt;<br>  &lt;input&gt;<br>  <strong>&lt;div&gt;0&lt;/div&gt;</strong><br> &lt;/div&gt;&lt;div&gt;<br>  &lt;span&gt;fahrenheit:&lt;/span&gt;<br>  &lt;input&gt;<br>  &lt;div&gt;32&lt;/div&gt;<br> &lt;/div&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p>After adding flush: &#39;post&#39; property, it consoles the below output, which has a celsius value updated.</p><pre>&lt;div id=&quot;app&quot; data-v-app=&quot;&quot;&gt;<br> &lt;div&gt;&lt;div&gt;<br>  &lt;span&gt;Celsius:&lt;/span&gt;<br>  &lt;input&gt;<br>  <strong>&lt;div&gt;1&lt;/div&gt;</strong><br> &lt;/div&gt;&lt;div&gt;<br>  &lt;span&gt;fahrenheit:&lt;/span&gt;<br>  &lt;input&gt;<br>  &lt;div&gt;32&lt;/div&gt;<br> &lt;/div&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><ul><li>immediate: In general, watchers do get executed only whenever there is a change in the data field on which we are spying. But in a certain case, where we want to force the watcher to run immediately, we can set immediate: true like below:</li></ul><pre>watch: {<br>    someMethod: {<br>      handler(newValue, oldValue) {<br>        .....<br>      },<br>      immediate: true<br>  }<br>}</pre><p>Other than these mentioned configurations, you can also start watchers conditionally using this.$watch() and stop watchers using $watchAPI functions whenever required.</p><h4>When to use computed v.s watchers?</h4><ul><li>Use <strong>computed property,</strong> when you want to perform computation based on any data field.</li><li>Use <strong>computed property,</strong> when you want to create a new data field based on computation which can be used for any other purpose as well.</li><li>Use <strong>watchers</strong>, when you want to spy/observe/monitor any data value.</li><li>Use <strong>watchers</strong>, when you want to perform any DOM mutation or data field updates.</li></ul><p>This is all I want to share about <strong>computed property</strong> and <strong>watchers</strong>. I hope this information helps you also to understand computed property and watchers without any confusion 🙂. Please feel free to comment on your views or any feedback if you have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6416ebfa18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JS Lookups & Errors]]></title>
            <link>https://srivastavaankita080.medium.com/understanding-js-lookups-errors-7d2ea1efdc0c?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2ea1efdc0c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[look-up]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Fri, 08 Oct 2021 09:01:34 GMT</pubDate>
            <atom:updated>2021-10-11T04:30:32.061Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a story of 2 friends(Jane &amp; Kurt) who are communicating with each other for a better understanding of Javascript Errors.</p><p><strong>Jane</strong>: Hello Kurt, How are you doing?</p><p><strong>Kurt: </strong>Hi Jane, I am doing good. Recently my project got over and I must say what great learning. By the way, how is your work going on these days?</p><p><strong>Jane: </strong>Yeah, It&#39;s going ok not that great though. I am struggling with Javascript and its concepts. I feel totally confused when I have to debug in Js. 🤯🤯</p><p><strong>Kurt: </strong>Hey, I really like Javascript❤️, I have learned so many good things about it in my last project. You know the best thing about Javascript is, once you understand the concept of Js, you will be amazed and fall for it.</p><p><strong>Jane:</strong> Seems like you love Javascript. I never felt like that, especially for Javascript. Javascript is very confusing for me. Will you help me in understanding few concepts?</p><p><strong>Kurt: </strong>Everything for Javascript💕. Tell me what is the most confusing thing for you. We will start from there first.</p><p><strong>Jane:</strong> Cool, then let’s talk about Javascript errors, why Javascript has different types of errors, e.g., ReferenceError, TypeError, etc.</p><p><strong>Kurt:</strong> This one is simple, if you just google you will get many answers in a <a href="https://stackoverflow.com/questions/12589391/difference-typeerror-and-referenceerror">stack overflow</a>. But hold on, If you read those answers you will just know when to get what errors but you will not understand how Js engine internally does this thing behind the scene. Let me try to explain how beautifully the JS engine handles the error internally. For understanding Js errors, let&#39;s first talk about Js look-ups.</p><p>When the JS engine executes the compiled code then it has to look up for each variable to check whether the variable you are using is declared or not. This look-up happen to consult JS scope. e.g.,</p><pre>var a = 100;<br>function foo() {<br> let b = 10;<br> return a+b;<br>}</pre><p>In the above, example when the engine starts executing <strong><em>return a+b </em></strong>then it will look up for variable <strong>a</strong> and <strong>b</strong> consulting scope, i.e., checking whether <strong>a</strong> and <strong>b</strong> are declared or not, which in our case <strong>b</strong> is present in the local scope and <strong>a</strong> is the global scope.</p><p><strong>Jane:</strong> Yeah, That much I understand that looking up for a variable is basically checking whether a variable is declared or not.</p><p><strong>Kurt: </strong>Good, If you know, but do you know Js does 2 different types of look-ups. The type of look-up the engine performs affects the outcome of the look-up.</p><p><strong>Jane: </strong>That’s something new, so tell me a bit more about the look-up types</p><p><strong>Kurt: </strong>Sure, Js engine performs <strong>LHS</strong> and <strong>RHS</strong> look, I think the full form is more sort of we know that its left hand and right-hand lookup.</p><p>LHS look-up happens <strong>when variable appears on the left side of the assignment operation</strong> &amp; RHS look-up appear on the right side (or not on the left side) of the assignment operator, that&#39;s what we understood when we hear LHS and RHS.</p><p>So, LHS you got it right but not to confuse you for RHS, you can also understand RHS as <strong>go get the value of a variable (no assignment).</strong></p><pre>1. var a = 100;<br>2. function foo() {<br>3.  let b = 10;<br>4.  return a + b;<br>5. }</pre><p>In the above example, lines 1 and 3 perform LHS look up as we don’t care what the current value of <strong>a</strong> and <strong>b</strong> instead we assign the value directly. And as per definition, variable <strong>a</strong> and <strong>b</strong> appear on the left side of the assignment operator. Line 4 concerns the current value of <strong>a</strong> and <strong>b</strong> and so it performs the RHS lookup as it&#39;s asking for go get the value of <strong>a</strong> and <strong>b</strong>.</p><p><strong>Jane: </strong>Clear, this was easy to understand, I got the difference between LHS and RHS.</p><p><strong>Kurt: </strong>Ok, so can you tell me how many LHS and RHS lookup happening in the below example:</p><pre>1. function foo(b) {<br>2.  console.log(b);<br>3. }<br>4. foo(4);</pre><p><strong>Jane:</strong> I know Kurt, there is just 1 RHS look-up happening that&#39;s it.</p><p><strong>Kurt:</strong> You are not completely right, yes there is one RHS look up but you miss few points here:</p><ul><li>line 4 is passing 4 to variable b (implicit param assignment), which is also an assignment for variable <strong>b</strong> which counts to 1 LHS.</li><li>line 4 is saying go get the value of <strong>foo</strong>, hence 1 RHS for getting the value of foo.</li><li>line 2 is saying go get the value for <strong>console.log</strong>, hence 1 RHS for getting the value of log method inside console object.</li></ul><p>A total of 2 LHS and 2 RHS lookup.</p><p>So the conversation between Engine and Scope happens more like this:</p><blockquote><strong>Engine:</strong> Hey Scope, I have an RHS reference for foo, do you know foo?</blockquote><blockquote><strong>Scope:</strong> Yes, compiler declared it as a function, You can use it.</blockquote><blockquote><strong>Engine:</strong> Cool, I am executing foo then</blockquote><blockquote><strong>Engine:</strong> Scope, I got an LHS look up for variable a, do you understand this variable?</blockquote><blockquote><strong>Scope:</strong> Yes, It’s a formal parameter for foo, here you go.</blockquote><blockquote><strong>Engine:</strong> Cool, thanks, Do you also know about console? I got an RHS reference for console.</blockquote><blockquote><strong>Scope:</strong> Hey yes, it’s a built in object, what you want from it?</blockquote><blockquote><strong>Engine:</strong> I was looking for log method inside console, is it there?</blockquote><blockquote><strong>Scope:</strong> Yes, it’s there you can use it.</blockquote><blockquote><strong>Engine:</strong> Sorry but I got an RHS reference again for a, just want to confirm whether its same formal parameter for foo, or is it changed?</blockquote><blockquote><strong>Scope:</strong> No problem engine, its same you can use it. No change.</blockquote><blockquote><strong>Engine:</strong> Thanks scope for resolving it for me.</blockquote><p><strong>Jane:</strong> Woah!! That was a long discussion that happened between engine and scope for such a small chunk of code. And I didn’t think that look-up will also be performed for functions and <strong>console.log</strong>, which is something surprising for me.</p><p><strong>Kurt: </strong>Yes, that&#39;s why I say Js does magic internally for us.<strong> </strong>Just imagine for our long codebase, how long the scope and engine conversation would look like 🤯, which was handled by Js so nicely 🙏.</p><p>I was also amazed when I first read about how the look-up happened internally 😇.</p><p><strong>Jane:</strong> That&#39;s all is good for theoretical knowledge Kurt, but we started discussing JS Errors why you are telling me theory, tell me something that will help us to understand errors.</p><p><strong>Kurt:</strong> Yeah be patient I am going there 😁. So we have 3 types of Javascript errors:</p><ul><li>Syntax Errors</li><li>Reference Errors</li><li>Type Errors</li></ul><p>I believe that Syntax errors are very much clear to most of us. So let’s discuss the other two. Time to reveal the concept 🤩🤩</p><p><strong>Reference Error:</strong></p><p>When the JS engine does an RHS lookup and scope tells the engine that the variable is undeclared, which results in scope resolution failure, it results in Reference Error.</p><blockquote>Scope resolution failure in RHS look up = Reference Error</blockquote><p>In the below example</p><pre>function foo(){<br> return a;<br>}</pre><p>We have an RHS lookup for variable <strong>a</strong>, the engine will communicate to scope to check if the variable is declared or not as it is an RHS lookup, scope responds back to say there is no variable for named <strong>a</strong>, which result in scope resolution failure.ie., <strong>Reference error</strong>.</p><p><strong>Note:</strong> In case of LHS lookup, if the engine found that the variable is undeclared, the scope being friendly will create one variable for the engine and will not result in Reference error, but only if you don’t use “<strong>Strict Mode</strong>” added in ES5 in your code. If “<strong>Strict Mode</strong>” is added then, LHS lookup will also result in a Reference error, similar to RHS scope resolution failure.</p><p>For example: In the below example, <strong>b</strong> is not declared anywhere in the code but still, you don’t get any reference error, because scope creates variable <strong>b</strong> even if you missed declaring it.</p><pre>function foo(){<br> b = 15;<br> console.log(b);<br>}</pre><pre>foo();</pre><pre>Output: 15</pre><p>But if you use strict, then you will end up getting reference errors.</p><pre>use &quot;strict&quot;<br>function foo(){<br> b = 15;<br> console.log(b);<br>}</pre><pre>foo();</pre><pre>Output: Reference Error</pre><p><strong>Type Error:</strong></p><p>When Js Engine performs an RHS look-up and scope responded positively on the look-up, after which you try to perform any <strong>illegal operation</strong> on the look-up value, it results in a type error.</p><blockquote>When there is a successful RHS look up but an impossible action is performed on the look up outcome value = Type Error</blockquote><p>In the below example</p><pre>var c = &quot;Hello Js&quot;<br>function foo() {<br> return c.someFunc();<br>}</pre><pre>foo();</pre><pre>Output: TypeError</pre><p>So here, the RHS lookup for variable <strong>c</strong> is successful and scope responded positively to the engine mentioning <strong>c</strong> is a variable. Now on this outcome, we are trying to perform a function call on a variable, which is not valid and hence it results in <strong>TypeError</strong>.</p><p><strong>Jane: </strong>😳😳 I searched a lot of places but I never exactly understood that this is happening behind the scene. Now, I understood why you explained Js look up before actually explaining the errors. This really helps 🙏🙏. I clearly understood whats the exact difference between Errors and all the lookup games.</p><p><strong>Kurt:</strong> 😎😎. No problem at all. Let me know in case if you want to know something else we can do small catch-ups like this always 🙂.</p><p>I gathered all the points and wrote this blog to go through the concepts whenever I want to recall them. I will be happy if anyhow it helps you and incase you want more blogs on JS topics, will try out adding more. Feedbacks are always welcome 🙂🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2ea1efdc0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Hashicorp Nomad and Consul — Part 4: Consul KV Store]]></title>
            <link>https://srivastavaankita080.medium.com/practical-hashicorp-nomad-and-consul-part-4-consul-kv-store-ef837e0e4ffc?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef837e0e4ffc</guid>
            <category><![CDATA[consul]]></category>
            <category><![CDATA[nomad]]></category>
            <category><![CDATA[key-value-store]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 12:21:15 GMT</pubDate>
            <atom:updated>2021-10-05T12:21:15.033Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Practical Hashicorp Nomad and Consul — </strong>Part 4: Consul KV Store</h3><p>Co-authored by <a href="https://medium.com/u/84ec3713d9f5">Navin Nair</a>, <a href="https://medium.com/u/9f8cb64bdd2d">Jawahar Suresh Babu S</a>, <a href="https://medium.com/u/1ce85f57d4ef">Manikandan S</a> and <a href="https://medium.com/u/54ba4cb45448">ARUN KUMAR</a></p><p>This is in continuation of previous three articles Part1, Part2 and Part3, If you came here directly, I will recommend to give a read for the previous 3 articles as well.</p><ul><li><a href="https://medium.com/navin-nair/practical-hashicorp-nomad-and-consul-a-little-more-than-hello-world-part-1-991d2a54fd64">Practical Hashicorp Nomad and Consul — A little more than Hello World (Part 1)</a></li><li><a href="https://medium.com/@arunlogo.kct/practical-hashicorp-nomad-and-consul-ci-cd-pipeline-to-deploy-the-api-and-webapp-part-2-c07117bbb27d">Practical Hashicorp Nomad and Consul — CI/CD Pipeline to deploy the API and WebApp Part 2</a></li><li><a href="https://medium.com/@jawaharsbs/practical-hashicorp-nomad-and-consul-monitoring-autoscaling-using-prometheus-grafana-part-3-8e032fbf1357">Practical Hashicorp Nomad and Consul - Monitoring &amp; Autoscaling using Prometheus &amp; Grafana (Part 3)</a></li></ul><p>But incase you completed the previous one and came here, I will give a brief about last three article and what we will do as part of this article, Let’s recall!! 😎😎</p><ul><li>In the first part, we discussed the steps to set up a 3-Tier application and deploying it in a Nomad/Consul cluster as part of a service mesh.</li><li>In the second part, we discussed about setting up the continuous deployment(CD) pipeline to get the code from the application, build it and deploy it to nomad cluster.</li><li>In the third part, we discussed about how we can add observability to our Nomad cluster &amp; service mesh and also setup auto-scaling based on load.</li><li>In this article, we will be discussing 2 ways to fetch configuration data from consul key-value store instead of hard coding it in the application.</li></ul><p>So, let’s get started!!</p><p>For keeping it simple, We will just remove port, context-path and greeting configurations from application.properties file and try to fetch these information from consul key value store.</p><p><strong>1.) Using spring cloud dependency in the application</strong></p><p><strong>Step1:</strong> This is the common step for both the ways, where we need to create key-value pairs in consul. You can create key value pair in consul using consul UI, which is running on port 8500.</p><ul><li>Click key/value option in the left navigation menu, you should be able to see below screen:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7XW7ZV02zhuZsEYDvoJ6g.png" /></figure><ul><li>Click on Create button present on the top right in the screen.</li><li>Now add the key value pair, and click on Save button. Please add the key in the same format <strong>config/&lt;application_name&gt;/&lt;key_name&gt;: &lt;value&gt;, </strong>just like how we did in the below screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHKYbRp51Faf9mbNroeLMQ.png" /></figure><p>Thats it!! you should be able to create your key value pair using consul UI.</p><p>There are lot of ways to create key-value pairs in consul kv store which can be checked <a href="https://learn.hashicorp.com/tutorials/consul/get-started-key-value-store?utm_source=consul.io&amp;utm_medium=docs">here</a>.</p><p><em>Optional: If you have too many key value that needs to be created then you can create key value using json file. Below are the steps for the same.</em></p><p><strong>Step1</strong>: This is the json file which have key-value in the format of <strong>config/&lt;application_name&gt;/&lt;key_name&gt;: &lt;value&gt;</strong></p><pre>[<br>  {<br>    &quot;key&quot;: &quot;config/consul_kv_demo/server.port&quot;,<br>    &quot;value&quot;: &quot;OTk2Ng==&quot;<br>  },<br>  {<br>    &quot;key&quot;: &quot;config/consul_kv_demo/server.servlet.context-path&quot;,<br>    &quot;value&quot;: &quot;L3BldGNsaW5pY2FwaS8=&quot;<br>  },<br>  {<br>    &quot;key&quot;: &quot;config/consul_kv_demo/greeting&quot;,<br>    &quot;value&quot;: &quot;IkphY2tBbmRKb2UxMjMi&quot;<br>  }<br>]</pre><p>After creating this, run the below command to create consul kv pairs</p><pre>consul kv import @&lt;path-to-the-json-file&gt;/properties.json</pre><p>In our case, the command looks like this:</p><pre>consul kv import <a href="http://twitter.com/envconsul">@consul</a>-kv-store/secrets/properties.json</pre><p>where <strong>consul-kv-store/secrets/properties.json</strong> is the path of the file.</p><p>You should be able to see the below key-value pairs in your consul</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPzBx2Du5HeMl0kQYLrN9A.png" /></figure><p>Note:</p><ul><li>The value present in the file needs to base64 encrypted value.</li><li>This key-value format is applicable only for this spring-cloud way of fetching config from consul kv store.</li><li>Your application_name need to be same what you will give in the application.properties file (<strong>spring.application.name=consul_kv_demo</strong>)</li></ul><p><strong>Step 2</strong>: Add the <strong>spring-cloud-dependencies</strong> and <strong>spring-cloud-starter-consul-config</strong> dependency in the <strong>pom.xml</strong> file.</p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;2020.0.0&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-consul-config&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>Note:</strong> Few versions of spring boot is not compatible with spring-cloud-dependencies, we used <strong>spring boot version 2.4.2</strong> and <strong>spring-cloud 2020.0.0</strong>, which is compatible to each other. You can check the compatibility <a href="https://spring.io/projects/spring-cloud">here</a>. Believe me, it took lot of time to figure out this 🤯🤯</p><p><strong>Step 3</strong>: Add the below configuration in application.properties file</p><pre>spring.application.name=&lt;application_name&gt;<br>spring.config.import=consul:&lt;consul_host&gt;:&lt;consul_port&gt;<br>spring.cloud.consul.discovery.health-check-interval=&lt;any_time_to_check_health&gt;<br>spring.cloud.consul.discovery.instance-id=&lt;any_instance_id&gt;:&lt;consul_port&gt;</pre><p>In our case, application_name is <strong>consul_kv_demo</strong> consul_host will <strong>172.16.1.101</strong> and consul_port is <strong>8500</strong>(default). So our configuration look like this:</p><pre>spring.application.name=consul_kv_demo<br>spring.config.import=consul:172.16.1.101:8500<br>spring.cloud.consul.discovery.health-check-interval=15s<br>spring.cloud.consul.discovery.instance-id=random:8500</pre><p><strong>Step 4</strong>: Add <strong>@EnableDiscoveryClient</strong> annotation in the main java file., PetClinicApplication.java (in our case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5r1ykVU4eIL3Y8MxX9m7Q.png" /></figure><p><strong>Step 5</strong>: Add <strong>@RefreshScope</strong> annotation in all the java file where <strong>@Value</strong> annotation is used so that on any key-value change the application refresh the value automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrmjG_lG26NKkD1Hh2to7A.png" /></figure><p><strong>Step 6</strong>: Now, we need to package the JAR, which can be done by 2 ways</p><p>a.) We can manually package the JAR file using the below command and use github to host the JAR file then directly use the path(raw) of the hosted jar file in the <strong>source</strong> parameter of <strong>artifact</strong> stanza in the nomad job file.</p><p>In case, you want to check the spring boot changes, you can check <a href="https://github.com/sankita15/spring-petclinic-rest">here</a>.</p><pre>mvn package</pre><p>Note: Incase, you want to check the entire job file for setting up manually packaged jar, you can check <a href="https://github.com/nairnavin/practical-nomad-consul/blob/main/consul-kv-store/jobs/petclinic-api.nomad">here</a>.</p><p>b.) Otherwise, we can make the changes in java source code as shown in example and use the pipeline shown in part 2 to build the jar and deploy it.</p><p>Thats it!!. This time your application should run using values you added in consul kv store. If yes, Congratulations 🎉🎉, our application is able to communicate and fetch config data from consul kv store.</p><p>You can try changing any value in the consul kv store and hit the api to reflect the changed value.This way you don’t need to package your JAR file or build it every time on any configuration changes because consul kv will detect the changes and provide the new value.</p><p>Though this way, we achieve the separation of config from the application code but this is more spring way of doing thing, where we need to use spring cloud dependencies to get it work and it involves code changes also. Let’s see the other way which is not very coupled with spring way of doing things and less code changes in spring boot project.</p><p><strong>2. ) Using Envconsul Binary</strong></p><p>In this way, we will use envconsul binary to fetch data from consul kv store.</p><p><strong>Step 1</strong>: First we need to create key value pairs in consul kv store, similar to how we did it previously in Step1.</p><p>Note: When we are using envconsul, key value pair can be in any format not necessarily to be in the below format(which was the case when using spring cloud dependencies):</p><p><strong>config/&lt;application_name&gt;/&lt;key_name&gt;: &lt;value&gt;</strong></p><p>But for simplicity, we will use the same format i.e., our key value pair look like this:</p><pre><strong>config/consul_kv_demo/greeting: &quot;Hello consul&quot;<br>config/consul_kv_demo/server.port: 9966<br>config/consul_kv_demo/server.servlet.context-path: /petclinicapi/</strong></pre><p><strong>Step 2</strong>: Download a pre-compiled, released version from the <a href="https://releases.hashicorp.com/envconsul/"><strong>envconsul releases</strong></a> page.</p><p><strong>Step 3</strong>: Extract the binary file and move the binary to your PATH.</p><p>In the <a href="https://github.com/nairnavin/practical-nomad-consul">Github example</a>, we have implemented the step2 and step3 on vagrant machine boot up, but if you are not using vagrant you can do it manually in your local.</p><p><strong>Step 4</strong>: This step is just to check whether envconsul set up is done and its listening to consul kv store properly or not. For this, run the below command which should give you all the key value pairs for a directory(config2).</p><pre>envconsul -prefix &lt;directory-name&gt; env</pre><p>In our case, the command looks like:</p><pre>envconsul -prefix config/consul_kv_demo env</pre><p><strong>Step 5</strong>: This step is optional incase you need to execute the JAR file manually using envconsul(where nomad jobs is not in picture) so it fetch the data from kv store. For this, we need to run the below command.</p><pre>envconsul --prefix &lt;directory_name&gt; java -jar &lt;jar-file-path&gt;</pre><p>In our case, the command looks like:</p><pre>envconsul --prefix config/consul_kv_demo java -jar envconsul_jar/spring-petclinic-rest-2.4.2.jar</pre><p>This way it will pick the config properties from consul kv store(ofcourse your consul needs to be running 😉) when you want to run the application manually(without nomad job).</p><p><strong>Step 6</strong>: Now the main step, we need to run the JAR file by using nomad job file, our task should look like this:</p><pre>task &quot;petclinic-api&quot; {<br>  driver = &quot;exec&quot;<br>  config {<br>    command = &quot;envconsul&quot;<br>    args    = [&quot;--config&quot;, &quot;local/envconsul.hcl&quot;, &quot;java&quot;, &quot;-jar&quot;, &quot;/tmp/spring-petclinic-rest-2.4.2.jar&quot;, &quot;-Xms256M&quot;, &quot;-Xmx256M&quot;, &quot;--nogui;&quot;]<br>  }<br>  artifact {<br>    source = &quot;https://github.com/sankita15/spring-petclinic-rest/raw/master/envconsul_jar/spring-petclinic-rest-2.4.2.jar&quot;<br>    destination = &quot;/tmp&quot;<br>  }<br>  template {<br>    data = &lt;&lt;EOH<br>      consul {<br>        address = &quot;172.16.1.101:8500&quot;<br>      }<br>      prefix {<br>        path = &quot;config/consul_kv_demo&quot;<br>      }<br>    EOH<br>    destination = &quot;local/envconsul.hcl&quot;<br>  }<br>  resources {<br>    cpu    = 500<br>    memory = 300<br>  }<br>  env {<br>    API_PORT = &quot;9966&quot;<br>  }<br>}</pre><p><strong>Explanation:</strong></p><pre>driver = &quot;exec&quot;</pre><ul><li>We are using <strong>exec instead of Java driver </strong>here, as we need to run the envconsul as part of nomad job and then envconsul will run the JAVA application (name: petclinic-api).</li></ul><pre>template {<br>    data = &lt;&lt;EOH<br>      consul {<br>        address = &quot;172.16.1.101:8500&quot;<br>      }<br>      prefix {<br>        path = &quot;config/consul_kv_demo&quot;<br>      }<br>    EOH<br>    destination = &quot;local/envconsul.hcl&quot;<br>  }</pre><ul><li>In the <strong>template</strong> stanza, we use <strong>data</strong> parameter to write all the configuration inline which we want to apply for envconsul. e.g.,</li></ul><ol><li>We gave <strong>consul-address</strong> because we want envconsul to check consul on 172.16.1.101:8500 because our consul is running here.</li><li>We gave <strong>prefix-path</strong> as config/consul_kv_demo because we want envconsul to check the JAR file configuration in the config/consul_kv_demo directory.</li></ol><p><strong>Note:</strong> If you have lot of such configuration for envconsul, then instead of using <strong>data</strong> parameter, you can use <a href="https://www.nomadproject.io/docs/job-specification/template#source"><strong>source</strong></a> parameter<strong> </strong>also.</p><ul><li>All the envconsul’s configuration that we got from data will be stored in a file <strong>envconsul.hcl</strong> and that’s what our destination tells us.</li></ul><pre>config {<br>    command = &quot;envconsul&quot;<br>    args    = [&quot;--config&quot;, &quot;local/envconsul.hcl&quot;, &quot;java&quot;, &quot;-jar&quot;, &quot;/tmp/spring-petclinic-rest-2.4.2.jar&quot;, &quot;-Xms256M&quot;, &quot;-Xmx256M&quot;, &quot;--nogui;&quot;]<br>  }</pre><ul><li>In the <strong>config</strong> stanza, we used “envconsul” for <strong>command</strong> parameter as we want to run envconsul, straight and simple 😁.</li><li>For the <strong>args</strong> parameter, we passed the following values:</li></ul><ol><li>- -config: “local/envconsul.hcl”</li></ol><p>This is to tell the job to pick up envconsul’s configuration from this location. If you remember, we created a config file using <strong>data</strong> parameter in the <strong>template</strong> stanza. we are using the same file here.</p><p>2. And then we gave the command to run the JAR file.</p><p>In case you want to check the entire Job file, you can check <a href="https://github.com/nairnavin/practical-nomad-consul/blob/main/envconsul-kv-store/jobs/petclinic-api.nomad">here</a>.</p><p><strong>Note:</strong></p><ul><li>This approach doesn’t need to do any changes in spring boot application.</li><li>In the first approach, if you change any value in consul key value pair, then it will take few seconds to reflect the new changed value in the application but your application will always be available without any downtime.</li><li>In second approach, if you change any value in the consul key value pair, then envconsul will restart the application, which make our application unavailable for a short duration(till the application gets boot up again). We can disable this feature and ask envconsul not to listen for any change in the application by passing <strong>— once</strong> flag.</li><li>envconsul also provide one more config as a workaround for the above downtime issue i.e., <strong>splay </strong>which can be set any time.e.g., <strong>splay = “30s”</strong>, then all the instances of your application will not reboot simultaneously, instead envconsul will reboot all the instances one by one by taking any random amount of time between 0 to 30s. Generally, high splay and multiple instance can reduce the downtime experience a lot but it still random so no downtime is not guaranteed.</li><li>There are lot to configure for envconsul which you can check <a href="https://github.com/hashicorp/envconsul">here</a>.</li></ul><p>That’s it folks. We discussed the 2 ways by which we can separate the configuration from our application source code. I tried to make it as simple as possible, hope it helps you all. 🙏🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef837e0e4ffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS Positioning]]></title>
            <link>https://srivastavaankita080.medium.com/css-positioning-a100a8817447?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/a100a8817447</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[css-positioning]]></category>
            <category><![CDATA[css-position]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 15:50:05 GMT</pubDate>
            <atom:updated>2020-10-13T15:50:05.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvQWW79jIX1XMq-jp4YtFg.jpeg" /><figcaption>From:- <a href="https://images.app.goo.gl/QNnkCybCm9VGzVNd8">https://images.app.goo.gl/QNnkCybCm9VGzVNd8</a></figcaption></figure><p>Are you also a full stack developer like me struggling with CSS code in your project? or looking for a UI developer for any css issues? if yes then reading this is worth for you. I promise I will try to make it as simple as possible and you just need basic understanding of css(what is css etc.). Let’s make our hand dirty with CSS 😊</p><p>CSS Positions are used to specify the type of positioning used for an element. There are 5 main types of CSS Positions:</p><ul><li>static (default)</li><li>relative</li><li>absolute</li><li>fixed</li><li>sticky</li></ul><p>Let’s talk about all of them one by one to make it clear.</p><ol><li><strong>static</strong>: This is the default CSS position property. It will align elements in the normal flow of execution .i.e., top, bottom, left, right and z-index will not work with this css position to adjust element. If you want to adjust elements with static positioning, you can use margin and padding.</li><li><strong>relative</strong>: This position property is used to adjust element with respect to its normal position. We can use top, left, right, bottom and z-index property with this position to adjust element positioning.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOq2Nd-QLnO2nNdDTB7tVw.png" /></figure><p>In the above scenario, we have 3 items in a container(green background) with some specific width and height. We have given <strong>position: relative</strong> to <em>item-2</em>, so that we can adjust <em>item-2</em>, relative to the its normal positioning. we have given <strong>top: 10px</strong> in the above scenario, which makes <em>item-2</em> to starts from 10px top to its normal positioning. Get your hands dirty by using different property like bottom, left, right and z-index in the below example 👇 👇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fembed%2Fpreview%2FQWyJoKq%3Fheight%3D600%26slug-hash%3DQWyJoKq%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fpen%2FQWyJoKq&amp;image=https%3A%2F%2Fassets.codepen.io%2F4801118%2Finternal%2Fscreenshots%2Fpens%2FQWyJoKq.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595176803%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c734e9229e82c9e12352305e2f2cf49/href">https://medium.com/media/7c734e9229e82c9e12352305e2f2cf49/href</a></iframe><blockquote><strong>Note</strong>: Negative values for top i.e., <strong>top: -10px</strong> is equal to <strong>bottom:10px</strong></blockquote><p>3. <strong>absolute</strong>: This position property is used to adjust element with respect to its closest parent’s element position(only if closest parent have position property). absolute position makes the child element to jump from its normal flow of execution .i.e., parent will assume child is not present there at all. Both parent and child should have position property to adjust the child element with respect to parent’s element position. Whichever is close to parent element will have position property, the child will be aligned with respect to that parent element.</p><p><strong>Example 1: Basic position absolute example.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZ4Ixv4nt17pUaMpkMPwrA.png" /></figure><p>In the above case, we have given <strong>position: absolute</strong> to <em>item-1</em> (first-child) because of which <em>item-1</em> jump from its normal flow of execution (container(parent) assumes that <em>item-1</em> doesn’t exists, that’s why it aligned rest of child(<em>item-2</em> and <em>item-3</em>) from top which results in overlapping of <em>item-1</em> and <em>item-2</em>). We have given <strong>top: 200px</strong> to move <em>item-1</em> to 200px from top otherwise <em>item-1</em> and <em>item-2</em> will get overlapped (you can try removing <strong>top: 200px</strong> to see if <em>item-2</em> is coming behind <em>item-1</em>) 👇 👇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fembed%2Fpreview%2FmdVQgKK%3Fheight%3D600%26slug-hash%3DmdVQgKK%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fpen%2FmdVQgKK&amp;image=https%3A%2F%2Fassets.codepen.io%2F4801118%2Finternal%2Fscreenshots%2Fpens%2FmdVQgKK.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595181117%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/da9c7fd8f8eeabc7ceffba184f693c75/href">https://medium.com/media/da9c7fd8f8eeabc7ceffba184f693c75/href</a></iframe><p><strong>Example 2: When immediate parent element not having position property.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRXz2mo3uqXv3lHX68C1aA.png" /></figure><p>In the above scenario, there is no position property on the immediate parent element(container) because of which it is considering the entire body element(entire height) as the parent and align the child element based on the body element. To make it more clear, I have given <strong>bottom: 0 </strong>to<strong> </strong>child <em>item-1</em>, which pushes the item out of the green container to the bottom of the main screen, because child <em>item-1</em> is aligned based on body element and not with the immediate parent element(container). You can give different properties to play more with it. 👇 👇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fembed%2Fpreview%2FdyGLYew%3Fheight%3D600%26slug-hash%3DdyGLYew%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fpen%2FdyGLYew&amp;image=https%3A%2F%2Fassets.codepen.io%2F4801118%2Finternal%2Fscreenshots%2Fpens%2FdyGLYew.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595692872%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/23f31de0198a6dbbc0d30e6007ecf2f6/href">https://medium.com/media/23f31de0198a6dbbc0d30e6007ecf2f6/href</a></iframe><p><strong>Example 3: When immediate parent element have position property</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnZ--lQyGxqjxUhBl4AFXQ.png" /></figure><p>In the above case, <em>item-1</em> is placed exactly at the bottom of green container because now the immediate parent (container) is having position property and <em>item-1</em> is set to <strong>bottom: 0</strong>. For making it more clear, the width and height of the green container is different than width and height of entire screen (visible via red borders). Try giving different height to container class and see how <em>item-1</em> will stick to bottom of the container 👇 👇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fembed%2Fpreview%2FPoZgPxw%3Fheight%3D600%26slug-hash%3DPoZgPxw%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fpen%2FPoZgPxw&amp;image=https%3A%2F%2Fassets.codepen.io%2F4801118%2Finternal%2Fscreenshots%2Fpens%2FPoZgPxw.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595693510%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b924cf95bb104f8b5dbdb7898ef5545/href">https://medium.com/media/9b924cf95bb104f8b5dbdb7898ef5545/href</a></iframe><blockquote><strong>Note</strong>: In case of <strong>position:absolute, </strong>if we don’t give width and height property to the element, then it will take just the required width and height to fit content.</blockquote><p>4. <strong>fixed</strong>: This position property is very similar to absolute position property as this also helps you aligning the child element but with respect to view-port. Element with <strong>position:fixed</strong> will not scroll at all.</p><p><strong>Example 1: Basic position fixed example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xtftCm38isM0JSviKznYQ.png" /></figure><p>In the above case, we have given <strong>position: fixed</strong> to green box(fixed-container) and we used left and top property for adjusting the green box. Try to scroll it to see the fixed property in the below example.👇 👇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fembed%2Fpreview%2FoNbOjKO%3Fheight%3D600%26slug-hash%3DoNbOjKO%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fpen%2FoNbOjKO&amp;image=https%3A%2F%2Fassets.codepen.io%2F4801118%2Finternal%2Fscreenshots%2Fpens%2FoNbOjKO.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595695217%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/480f0d4733e786d32b7e4ddeace9bf8a/href">https://medium.com/media/480f0d4733e786d32b7e4ddeace9bf8a/href</a></iframe><p>5. <strong>sticky: sticky</strong> property is the new property and not yet supported by many <a href="https://caniuse.com/#feat=css-sticky">browsers</a>. It works based on the mouse movement. As the name suggests, you can made an item stick to a position even when you scroll the page.</p><p><strong>Example 1: Basic position sticky example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qy0QWi-4uygm3Xb9yf7aYg.png" /></figure><p>In the above example, the 3rd child item is having <strong>position: sticky</strong> and it will scroll till 50px from the top and then get sticked at the top. As this position property based on the mouse movement, so it will be easier to understand if you play with the example below. 👇 👇</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fembed%2Fpreview%2FzYrXrNM%3Fheight%3D600%26slug-hash%3DzYrXrNM%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsankita15%2Fpen%2FzYrXrNM&amp;image=https%3A%2F%2Fassets.codepen.io%2F4801118%2Finternal%2Fscreenshots%2Fpens%2FzYrXrNM.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595696505%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/51252d4ea315a9538f3a2a342601449d/href">https://medium.com/media/51252d4ea315a9538f3a2a342601449d/href</a></iframe><p>That’s it about the css positioning. Please let me know if it helps you in understanding the position property or if you have any feedback about the writing. Happy Positioning 😊😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a100a8817447" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 — Beginner’s Guide Contd.]]></title>
            <link>https://srivastavaankita080.medium.com/es6-beginners-guide-contd-4d02358e3f94?source=rss-ddb9d07b4919------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d02358e3f94</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6-in-depth]]></category>
            <dc:creator><![CDATA[ankita srivastava]]></dc:creator>
            <pubDate>Tue, 28 May 2019 11:00:08 GMT</pubDate>
            <atom:updated>2019-05-28T11:00:08.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>ES-6 — Beginner’s Guide — Part 2</h3><p>I will be covering below topics as the PART-2 section of ECMAScript-6 Beginner’s guide. Here is the PART-1 section link <a href="https://medium.com/@srivastavaankita080/ecmascript-6-beginners-guide-60ac3d6c5ac8">https://medium.com/@srivastavaankita080/ecmascript-6-beginners-guide-60ac3d6c5ac8</a>.</p><ul><li>What is Destructured Assignments, Rest Parameters, Default Parameters?</li><li>Working with Arrow Function, Promises &amp; Fetch, Async &amp; Await.</li><li>ES6 class syntax &amp; Inheritance</li></ul><p>So, let’s start with the above topics and explore more into ES6.</p><h3><strong>Destructured Assignments</strong></h3><p>Destructured Assignments are performed on arrays &amp; objects. It is quite clear from its name i.e. you will destructure the values present inside the array/objects.</p><p>For Arrays destructuring, it will match the index positioning of values.</p><pre><strong>const </strong>employee= [&#39;John&#39;, &#39;Peter&#39;, &#39;Mark&#39;, &#39;Frank&#39;, &#39;Tom&#39;];<br><strong>const </strong>[first,,third,,,] = employee;<br>console.log(first,&#39;,&#39;, third);</pre><pre>Output: John, Mark</pre><p>if there is no requirement exist where you need entire array then you can have this way of destructuring:</p><pre><strong>const </strong>[first,,third,,,] = [&#39;John&#39;, &#39;Peter&#39;, &#39;Mark&#39;, &#39;Frank&#39;, &#39;Tom&#39;];<br>console.log(first,&#39;,&#39;, third);</pre><pre>Output: John, Mark</pre><p>In Object destructuring, it will match the values of the object to the keys instead of index positioning.</p><pre><strong>const </strong>person = {<br>    firstName: &#39;John&#39;,<br>    lastName: &#39;Peter&#39;,<br>    age: 23,<br>    gender: &#39;Male&#39;,<br>    qualification: &#39;BCA&#39;<br>};<br><br><strong>function </strong>printPersonDetails({firstName, age, qualification}) {<br>    <strong>return </strong>`${firstName} is ${age} years old and is qualified in  ${qualification}.`<br>}<br><br>console.log(printPersonDetails(person));</pre><pre>Output: John is 23 years old and is qualified in BCA.</pre><h3><strong>Rest Parameters</strong></h3><p>Rest parameters allow passing as many parameters as you want. If there is unknown no. of parameters, this can be very helpful. It basically holds all the passed arguments in an array and then you can access it in following way.</p><pre><strong>function </strong>addNumbers(...numbers){<br>    <strong>let </strong>sum=0;<br><br>    console.log(numbers[0]);<br>    console.log(numbers[1]);<br>    console.log(numbers[2]);<br><br>    <strong>for</strong>(<strong>let </strong>number <strong>of </strong>numbers){<br>        sum += number;<br>    }<br><br>    console.log(`sum of all numbers ${sum}`);<br>}<br><br>addNumbers(1,2,3);<br>addNumbers(1,2); /*as there is not 3rd argument it will print undefined */</pre><pre>Output: 1<br>        2<br>        3<br>        sum of all numbers 6<br>        1<br>        2<br>        undefined<br>        sum of all numbers 3</pre><h3><strong>Default Parameters</strong></h3><p>Default parameters are the parameters which already have default values. So while using the default parameters if you are not assigning any values, it will not give undefined results because the default value is always there as output.</p><pre><strong>function </strong>printPersonDetail(name = &#39;John&#39;, age= 23){<br>    console.log(`${name} is ${age} years old.`)<br> }<br><br>printPersonDetail();</pre><pre>Output: John is 23 years old.</pre><h3><strong>Arrow Functions</strong></h3><p>In ES5 we used <strong>function</strong> keyword for creating functions, which got changed with ES6. Now we can create functions using arrow function ( <strong>=&gt;</strong> ) and the syntax is quite handy!!</p><p>Let’s have a comparison of function syntax in both ES5 &amp; ES6 way to get more clarity.</p><p>In ES5</p><pre><strong>const </strong>printPersonDetail = <strong>function</strong>(name, age){<br>    console.log(`${name} is ${age} years old.`)<br>};</pre><pre>printPersonDetail(&#39;John&#39;,23);</pre><p>In ES6</p><pre><strong>const </strong>printPersonDetail = (name = &#39;John&#39;, age= 23) =&gt; console.log(`${name} is ${age} years old.`);</pre><p>Make sure to add curly braces after arrow function if you have more than one line of code in your function.</p><p>Arrow function brings a lot more conciseness and readability in your code. Unlike in normal function, it eliminates the need for binding <strong>this </strong>keyword<strong>. </strong>In arrow function, <strong>this</strong> keyword will always have meaning from its original context so you don’t need to go &amp; do explicit binding of <strong>this </strong>keyword.</p><h3><strong>Promises &amp; Fetch</strong></h3><p>Promises are objects which handles asynchronous operations and results in resolution or rejection. We can add multiple conditions depending on promise resolution or rejection value using <strong>then</strong> keyword. A promise can be in any of the 3 states at a time:</p><p>a.) pending -&gt; execution of promise started but not yet fulfilled or rejected.</p><p>b.) fulfilled -&gt; execution of promised completed successfully.</p><p>c.) rejection -&gt; execution of promise failed because of some error.</p><p>Fetch function is used for loading data from an API. It takes 2 parameters, the first one is the API itself and the second one is an object, from which you can change the different setting while loading data.</p><p>Generally, you will find promise usages more with <strong>fetch</strong> but there are other ways also. let’s see an example of using fetch with a promise to see its practical usage:</p><pre><strong>const </strong>data = () =&gt; {<br>     <strong>return </strong>fetch(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;)<br>         .then(response =&gt; response.ok ? response.json() : Promise.reject())<br>         .then(json =&gt; { <strong>return </strong>`${json.title} is completed or not ? -&gt; ${json.completed}`})<br>};<br><br>data().then(console.log)</pre><p>So, what is happening here is :</p><ol><li>data is a variable which is holding the value being returned by fetch call.</li><li>fetch is calling a random API, and if the fetching of data from <em>‘</em><strong><em>https://jsonplaceholder.typicode.com/todos</em></strong><em>&#39; </em>is successful ( status = 200 ok) then the promise is resolved and you will get data in JSON format and you will move to other <strong>then</strong> statement where we are returning the message. Promise will be in the fulfilled state.</li><li>if suppose there is some error in fetching the data from the above API then it will reject the promise (Promise.reject()). Promise will be in rejection state.</li><li>once the promises in fetch are handled then it will move to last <strong>then</strong> statement which will print the value of data returned by fetch call.</li></ol><p>There are a lot more we can do with the JSON data that we get after promise resolution or rejection. For Example:</p><pre><strong>const </strong>data = () =&gt; {<br>    <strong>return </strong>fetch(&#39;https://jsonplaceholder.typicode.com/&#39;)<br>        .then(response =&gt; response.ok ? response.json() : Promise.reject())<br>        .then(json =&gt; json.filter(user =&gt; user.title === &#39;delectus aut autem&#39;)[0])<br>        .then(msg =&gt; { <strong>return </strong>`${msg.title} is completed or not ? -&gt; ${msg.completed}`})<br>        .catch(status =&gt; { <strong>return </strong>status} )<br>};<br><br>data().then(console.log)</pre><p>If any error occurs while fetching the response it stops its execution of then and moves to catch block.</p><h3><strong>Async &amp; Await</strong></h3><p><strong>async keyword</strong> is used for asynchronous function. Now, the asynchronous function is something whose execution flow is not dependent on the main program flow i.e., it might have some parallel code execution. But its code is quite similar to a normal function, just we need to write async keyword at the start of the function to indicate that this function is asynchronous in nature.</p><p>So now we understood async functions and it may be possible that executing any particular line of the asynchronous function(say X) takes more time and there will be some other code(say Y) dependent on the result of function X. Here comes the need to <strong>await</strong> keyword. <strong>await keyword</strong> can be used here to pause or wait for any further code execution till that particular line code execution finishes successfully. Let’s have a look at the code to understand it practically.</p><pre><strong>const</strong> data = <strong>async</strong> () =&gt; {<br>             <strong>const</strong> response = <strong>await</strong> <strong>fetch</strong>(&#39;<a href="https://jsonplaceholder.typicode.com/todos/1&#39;">https://jsonplaceholder.typicode.com/todos/1&#39;</a>);<br>             <strong>const</strong> value = <strong>await</strong> response.json();<br>             console.log(value);<br>        };<br>data();</pre><p>In the above example, data is an asynchronous function as its flow of execution is not synchronous( because fetch call &amp; converting the response to JSON response might take more time than other lines of code present in data function) so for indicating that we used the async keyword.</p><p>We used await before the fetch call because we want to pause the execution of converting the response to JSON response(response.json()) till the successful execution of fetch call otherwise response variable will be holding undefined which results in an undesired result.</p><h3><strong>ES6 Class Syntax &amp; Inheritance</strong></h3><p>ES6 classes offer much cleaner and better syntax for writing code and handling inheritance compared to ES5 way of writing classes. It simply provides a better syntax for dealing with the prototype(e.g., adding function to prototypes, prototype inheritance) but does not introduce any new object-oriented model to JS.</p><p>ES5 way of writing classes:</p><pre><strong>var </strong>Dog = <strong>function</strong>(name , color) {<br>    <strong>this</strong>.name = name;<br>    <strong>this</strong>.color = color;<br>};<br>    Dog.prototype.getDogDetails = <strong>function</strong>(){<br>        <strong>return </strong>`${<strong>this</strong>.name} is ${<strong>this</strong>.color} in color.`<br>    };<br><br><strong>var </strong>dog = <strong>new </strong>Dog(&#39;Tom&#39;, &#39;White&#39;);<br>console.log(dog.getDogDetails());</pre><p>So here you wrote a function <strong>Dog </strong>which is basically acting as a fake class, and then for writing function, we need to add getDogDetails function to the prototype of Dog function.</p><p>But in ES6. the syntax is quite cool &amp; easy to write:</p><pre><strong>class </strong>Dog {<br><br>    <strong>constructor</strong>(name, color) {<br>        <strong>this</strong>.name = name;<br>        <strong>this</strong>.color = color;<br>    }<br><br>       getDogDetails() {<br>            <strong>return </strong>`${<strong>this</strong>.name} is ${<strong>this</strong>.color} in color.`;<br>        }<br>}<br><br><strong>let </strong>dog = <strong>new </strong>Dog(&#39;Tom&#39;, &#39;White&#39;);<br>console.log(dog.getDogDetails());</pre><p>We are creating a Dog class using the <strong>class </strong>keyword<strong>. </strong><em>name</em> &amp; <em>color</em> are the constructor properties of Dog class. In the background, the <em>getDogDetails</em> function is assigned to the Dog class prototype which is handled by ES6, we don’t need to do it explicitly which results in quite clearer code.</p><p>So, now you can compare how ES6 reduces our effort of creating the class. When it comes to inheritance, ES6 way of writing class is like a boon as it saves us from writing complex code with nasty syntax. Let’s see an example to compare the way of inheritance done in ES5 v/s ES6:</p><pre><strong>var </strong>Dog = <strong>function</strong>(name , color) { /* step1 */<br>    <strong>this</strong>.name = name;<br>    <strong>this</strong>.color = color;<br>}; /* step1 finished */<br><br>Dog.prototype.getDogDetails = <strong>function</strong>(){  /* step2 */<br>    <strong>return </strong>`${<strong>this</strong>.name} is ${<strong>this</strong>.color} in color.`<br>};  /* step2 finished */<br><br><strong>var </strong>WhiteDog = <strong>function </strong>(name, color) { /* step3 finished */<br>    <strong>this</strong>._super.call(<strong>this</strong>, name, color);<br>};  /* step3 finished */<br><br>WhiteDog.prototype = Object.create(Dog.prototype); /* step4 */<br><br>WhiteDog.prototype.constructor = WhiteDog; /* step5 */<br><br>WhiteDog.prototype._super = Dog; /* step6*/<br><br><strong>var </strong>whiteDog = <strong>new </strong>WhiteDog(&#39;Tom&#39;, &#39;White&#39;);<br>console.log(whiteDog.getDogDetails());</pre><p>I know the above code is a bit clumsy 😕 . Let me explain this so that you can understand the effort that got reduced with ES6 class syntax.Step1 &amp; Step2 should be clear to you as I already explained it in the above example.</p><ol><li>Step 3 is the creation of WhiteDog class in ES5 way, <strong><em>this._super.call(this, name, color); </em></strong>is used<strong><em> </em></strong>to pass the variable value to its superclass. We are calling <strong>call method</strong> &amp; passing <strong>this keyword</strong> so that new context(specific to child class) of <strong>this</strong> is set.</li><li>In step 4, we are setting the Child class prototype to be equal to Parent class.</li><li>In step 5, we are assigning child class constructor to its own prototype.</li><li>In step 6, we are assigning the Dog class as the superclass for WhiteDog class.</li></ol><p>Now, let’s see ES6 way of writing class:</p><pre><strong>class </strong>Dog {<br><br>    <strong>constructor</strong>(name, color) {<br>        <strong>this</strong>.name = name;<br>        <strong>this</strong>.color = color;<br>    }<br><br>       getDogDetails() {<br>            <strong>return </strong>`${<strong>this</strong>.name} is ${<strong>this</strong>.color} in color.`;<br>        }<br>}<br><br><strong>class </strong>WhiteDog <strong>extends </strong>Dog {<br>    <strong>constructor</strong>(name, color){<br>        <strong>super</strong>(name, color);<br>    }<br>}<br><br><strong>let </strong>whiteDog = <strong>new </strong>WhiteDog(&#39;Tom&#39;, &#39;White&#39;);<br>console.log(whiteDog.getDogDetails());</pre><p>Let we walk through the code once to explain to you:</p><ol><li>A Dog is the Parent class which has a name and color property and getDogDetails behavior in it.</li><li>WhiteDog is the child class which is inheriting parent class by using <strong>extends</strong> keyword &amp; because of that, a child class can use parent class properties &amp; behavior.</li></ol><p>Cool!! This code looks quite neat &amp; clean &amp; easy to understand 😊 . Now, I guess you can clearly see how much effort got reduced because of ES6 class syntax.</p><p>So, I covered all the topics that are required to start working with ES6 &amp; I hope you enjoyed it. ES6 is quite popular these days but yet there are some ES6 syntax which is not yet supported by some browsers and for that we need to do transpiling of our ES6 code. It&#39;s just converting the ES6 code that you wrote to ES5 so that browser supports it and a lot of tools are available for it like <strong>babel</strong> etc. Let me know if you want me to write, for setting up the babel tool for ES6 transpiling. Happy coding 😊 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d02358e3f94" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>