<?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 Priyanka Jacob on Medium]]></title>
        <description><![CDATA[Stories by Priyanka Jacob on Medium]]></description>
        <link>https://medium.com/@priyanka.jaccob?source=rss-75ce6f022eb2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uKBFcznZu-X0kI-g</url>
            <title>Stories by Priyanka Jacob on Medium</title>
            <link>https://medium.com/@priyanka.jaccob?source=rss-75ce6f022eb2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 23 May 2026 16:24:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@priyanka.jaccob/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[Reasoning Coding Challenges 2023 in Javascript]]></title>
            <link>https://medium.com/@priyanka.jaccob/reasoning-coding-challenges-2023-in-javascript-d4044b547a9d?source=rss-75ce6f022eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4044b547a9d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[this-keyword]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <dc:creator><![CDATA[Priyanka Jacob]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 11:05:51 GMT</pubDate>
            <atom:updated>2023-06-12T11:07:07.791Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there!<br>I am going to take you through detail explanation of two reasoning coding challenges I faced in an interview in 2023.<br>Heads Up! I have detailed a lot here because I wanted to understand from the smallest detail for the reason of getting particular output. Hence you may get bored by the end of reading. Only if you are looking to understand every smallest detail here, I suggest you to go through this article. Because if you are only looking to get 2–3 liners of the reason, I suggest you check any other article or go through a video online. This is just to save your time :)</p><p>So you decided to still read? Yeaaahh I am excited that you are going to read even the minute detail now…let’s get started!</p><h3><strong>Challenge 1 : Scoping/Closure/Asynchronous Javascript</strong></h3><pre>var div = document.querySelector(&#39;.foo&#39;)<br>   div.addEventListener(&#39;click&#39;, function() {<br>    this.innerHTML = &#39;Foo&#39;;<br>   });<br><br><br>   var div2 = document.querySelector(&#39;.foo2&#39;)<br>   div2.addEventListener(&#39;click&#39;, () =&gt; {<br>    this.innerHTML = &#39;Foo&#39;;<br>   });</pre><p>Result: The first event handler correctly changes the text of the div, whereas the second doesn’t.</p><h4><strong>Task 1 : Explain why the code is returning an incorrect result.</strong></h4><p>Here, there are some JavaScript concepts that we need to understand to answer the “why” for this output.</p><blockquote>1. Scoping</blockquote><p>“Scope” refers to availability of variables/functions in certain parts of the code.</p><p>Variables declared using the “var” keyword can have a function scope or global scope.</p><p>In the above scenario, the variable “i” is not declared inside any function and hence it has a global scope, which means that it is also accessible outside the for loop block.</p><pre>// i is accessible here<br>for (var i = 0; i &lt; arr.length; i++) {<br>….<br>}<br>// i is accessible here also</pre><p>Conclusion from here =&gt;<strong> variable “i” is in the global scope in the above program.</strong></p><blockquote>2. Closure</blockquote><p>A closure is formed when a function tries to access variables outside of its scope.</p><p>With the concept of closure, we have a function binded with its lexical environment(/scope).</p><p>In the above program, a closure is formed by the below callback function given in setTimeout:</p><pre>function() {<br>  console.log(&#39;Index: &#39; + i + &#39;, element: &#39; + arr[i]);<br>}</pre><p>This is formed because the callback function tries to access variables “i” and “arr” which are outside of its own scope.</p><p>Hence, there is a closure with the statements inside this function which is the <em>console.log </em>statement here, along with variables it needs which is “i” &amp; “arr” from its lexical parent.</p><p>If we are to draw it for understanding purpose, it would be like the below :</p><p><strong>Closure {</strong></p><p><em>// statements</em></p><p><em>console.log(‘Index: ‘ + i + ‘, element: ‘ + arr[i]);</em></p><p><em>// lexical environment variables</em></p><p><em>i (ex: Reference to memory location 0x123)</em></p><p><em>arr (ex: Reference to memory location 0x124)</em></p><p><strong>}</strong></p><p>Conclusion from here =&gt;<strong> There is a closure formed by the Callback function with variables “i” and “arr” (having memory references of them). Note that here all callback functions have same memory reference of “i”</strong></p><blockquote>3. Asynchronous Javascript</blockquote><p>Timer is not a feature provided by Javascript Engine but a feature of the browser which we are using in the program above using the “setTimeout” function provided by web apis (that are part of the Javascript runtime environment)</p><p>(In the context of running javascript outside the browser i.e., using node.js in the backend, this timer feature would be accessible via setTimeout function provided by C++ APIs which are present in Node js runtime environment)</p><p>Similar to timer, we have other features like window console, DOM APIs to access the DOM, fetch apis etc provided by this web apis.</p><p>When the loop runs above, the javascript interpreter does not wait for the setTimeout to complete, instead moves callback function of setTimeout during each iteration to another area (part of Javascript runtime environment)</p><p>In JAVASCRIPT RUNTIME ENVIRONMENT</p><p>CB1 with it’s closure referencing “i” and “arr”</p><p>CB2 with it’s closure referencing “i” and “arr”</p><p>CB3 with it’s closure referencing “i” and “arr”</p><p>CB4 with it’s closure referencing “i” and “arr”</p><p>And, execution continues in the main thread for the non blocking part of code.</p><p>As a result, the value of variable “i” in memory becomes “4” at the end of the for loop.</p><p>Now after 3 seconds, the callback function is moved to the callback queue. As the callstack is empty, the event loop takes the first item from the callback queue and places it in the callstack.</p><p>From the closure the callback function had formed with memory reference of “i” and “arr”, Javascript tries to read the values and replaces “i” and “arr[i]” in the console.log statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qjiB8RqTJYBjOe22" /></figure><p>While doing so, it understands that the value of “i” is 4. And the value of arr is [10,12,15,21].</p><p>Hence, it prints Index: 4, element: undefined to the screen as “i” is 4 and arr[4] is “undefined”.<br>As this continues (even loop taking next statement from callback queue and placing in callstack), the same statement gets printed.</p><p>Therefore it prints Index: 4, element: undefined four times to the screen.</p><h4><strong>Task 2 : Update the code to achieve the desired output</strong></h4><h4>METHOD 1 (prior to ES6)</h4><p>This can be solved by creating a local copy of the global scope variable inside the callback function and returning a function from this (this step is needed because setTimeout expects a function as first argument), so that closure is created with that variable instead of global scope variable.</p><p>There are two closures created here</p><ol><li>One is with global scope variable “arr”</li><li>Another is with the variable “x” from outer scope — i.e., from function “printMe”</li></ol><pre>const arr = [10, 12, 15, 21];<br>for (var i = 0; i &lt; arr.length; i++) {<br>  function printMe(x) {<br>    return function (){<br>    // Here, a closure is created with parent&#39;s variable &quot;x&quot; instead of the global scope variable &quot;i&quot; as earlier. And closure is also created with global scope variable &quot;arr&quot;<br>    console.log(&#39;Index: &#39; + x + &#39;, element: &#39; + arr[x]);<br>    }<br>  }<br>setTimeout(printMe(i), 3000)<br>}</pre><p>Hence, we get the desired output as below</p><p>Index: 0, element: 10</p><p>Index: 1, element: 12</p><p>Index: 2, element: 15</p><p>Index: 3, element: 21</p><h4>METHOD 2</h4><p>With es6 “let” which has<strong> block scope</strong> , hence at each iteration of the loop, a new memory location is created for “i” allowing it to hold the current value for that iteration. This ensures that each iteration of the loop operates with a separate and distinct value of i. And, the callback function forms a closure with those new copies and “arr” each time during loop iteration.</p><pre>const arr = [10, 12, 15, 21];<br>for (let i = 0; i &lt; arr.length; i++) {<br>  setTimeout(function() {<br>    console.log(&#39;Index: &#39; + i + &#39;, element: &#39; + arr[i]);<br>  }, 3000);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KLyT90ruLv60lOro" /></figure><p>And, as a result javascript environment has the below:</p><p>CB1 with referencing for i’s value during iteration 1 and referencing for “arr”</p><p>CB2 with referencing for i’s value during iteration 2 and referencing for “arr”</p><p>CB3 with referencing for i’s value during iteration 3 and referencing for “arr”</p><p>CB4 with referencing for i’s value during iteration 4 and referencing for “arr”</p><p>Hence, when event loop takes each of these from callback queue which are in first in first out order and places them to call stack one by one and while they get executed, we get the below output:</p><p>Index: 0, element: 10</p><p>Index: 1, element: 12</p><p>Index: 2, element: 15</p><p>Index: 3, element: 21</p><h3>Challenge 2: Function Context</h3><pre>var div = document.querySelector(&#39;.foo&#39;)<br>   div.addEventListener(&#39;click&#39;, function() {<br>    this.innerHTML = &#39;Foo&#39;;<br>   });<br><br><br> var div2 = document.querySelector(&#39;.foo2&#39;)<br>   div2.addEventListener(&#39;click&#39;, () =&gt; {<br>    this.innerHTML = &#39;Foo&#39;;<br>   });</pre><p>Result: The first event handler correctly changes the text of the div, whereas the second doesn’t.</p><h4><strong>Task 1 : Explain why first works and second doesn’t</strong></h4><p>Inside a normal function, the value of “this” is based on how this function is called, not on how this function is defined.</p><p>Arrow functions create a closure over the “this” value of the enclosing execution context, “this” is set to what it was when the function was created.</p><p><strong>Event Handlers</strong></p><p>Whenever we attach a handler function to an element using <em>addEventListener()</em>, the value of “this” inside the function will be a reference to the element or in other words, when we add an event handler to an element via Javascript code, “this” refers to the DOM element that generated that event.</p><p><em>Default binding for a callback function (if it is a normal function) in addEventListener is the html element.</em></p><p>Above case stands true for normal functions. Hence this is the reason the first event handler works. As the value of “this” — is the HTML element with id as “foo”. Hence on click of the element, it changes the element’s text to “Foo”.</p><p>“This” keyword when used inside the arrow function takes its value from the outer scope, in this code snippet, “this” inside click handler arrow function is referring to the “window” object instead of the div element.</p><p>This is the reason why, on clicking the div with id as “foo2”, we do not see any text change in the UI.</p><h4><strong>Task 2 : Does the second actually do anything? If so, what is it modifying?</strong></h4><p>On the click of the div element with id “foo2”, the second code snippet is modifying the “window” object.</p><pre>var div2 = document.querySelector(&#39;.foo2&#39;)<br>div2.addEventListener(&#39;click&#39;, () =&gt; {<br>this.innerHTML = &#39;Foo&#39;;<br>console.log(this) //Notice below that &quot;innerHTML&quot; is attached to &#39;window&#39; object<br>});</pre><p>Here, line 3 <em>this.innerHTML = ‘Foo’</em> is modifying the “window” object. It is attaching the key “innerHTML” with value ‘Foo’ in the “window” object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxJ9iHqwffloLy1dGahM1Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4044b547a9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add authorization for backend apis from the front-end application?]]></title>
            <link>https://medium.com/@priyanka.jaccob/how-to-add-authorization-for-backend-apis-from-the-front-end-application-c52dce90f6e?source=rss-75ce6f022eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c52dce90f6e</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Priyanka Jacob]]></dc:creator>
            <pubDate>Sat, 20 May 2023 06:53:46 GMT</pubDate>
            <atom:updated>2023-05-20T06:55:58.858Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, there!<br>I’m here to write a small story on a simple task UI devs would need to setup, that is how to add Authorization for backend apis from the front-end application.</p><p>For security reasons, backend apis would have an authorization check added from their end for all their apis. <br>There are different ways of authorizing the requests, if it is a basic method chosen, then it would be a username &amp; password based authentication performed while calling these apis.</p><p>From postman, we can initiate basic auth in a request as below (once we have the username and password in hand).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*Feg4iYoObWP1Y04mdf3-iQ.png" /></figure><p>If you notice using the <em>‘code’</em> option, the Authorization parameter passes a <strong>‘Basic &lt;encodedtext&gt;’</strong> instead of username and password as we expected.<br>That’s confusing?!</p><p>So, what happens is that <strong>username:password</strong> is base-64 encoded and then passed as authorization header in request. This encoded item is what we call <strong>“token” </strong>usually.</p><p>Steps to be followed for UI dev :</p><p>a) First check with backend dev what kind of request authorization method are they following for their apis. <br>If it is confirm as “Basic Auth”, get the ‘username’ and ‘password’ from them.<br>b) Encode ‘username:password’ to <a href="https://www.base64encode.org/">base-64 format </a>and save it as (for example: BACKEND_API_AUTH_TOKEN) in the config file.<br>c) While making the backend api call, add to the headers parameter this token.</p><pre>// helper file<br><br>import { set } from &#39;lodash&#39;;<br><br>const addApiHeaders = () =&gt; {<br>  const headers = {}<br>  if(process.env.BACKEND_API_AUTH_TOKEN) {<br>    set(headers,&#39;Authorization&#39;,`Basic ${process.env.BACKEND_API_AUTH_TOKEN}`);<br>  }<br>  return ({<br>  ...headers,<br>  &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  })<br>}</pre><p>So the fetch call would look like :</p><pre>//.........<br>fetch(url, {<br>  headers : addApiHeaders(),<br>  //........<br>})</pre><blockquote>While configuring api authorization in front end web application, it is better to avoid having username and password exposed in config files and then encode it run-time to pass in header param. This is because, this is directly exposing the username and password. <br>As per the method followed in this demo, since it is already base64 encoded we only save an encoded text in config.</blockquote><blockquote>This token can also be encrypted further with a secret that only frontend &amp; backend team is aware of for more security.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c52dce90f6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a simple react application using webpack]]></title>
            <link>https://medium.com/@priyanka.jaccob/creating-a-simple-react-application-using-webpack-90a5e4f6f85d?source=rss-75ce6f022eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a5e4f6f85d</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Priyanka Jacob]]></dc:creator>
            <pubDate>Sat, 20 May 2023 04:20:24 GMT</pubDate>
            <atom:updated>2023-05-20T06:07:52.805Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a simple React application using webpack from scratch</h3><p>This is inspired from <a href="https://jsramblings.com/creating-a-react-app-with-webpack/">https://jsramblings.com/creating-a-react-app-with-webpack/</a> post which helped me understand how to create a simple react (v18) application from scratch without using CRA and using webpack (v5), babel etc.</p><p>Though<strong> ‘create-react-app’</strong> does everything for us, with lot of encapsulated information, we would not understand what’s happening under the hood.<br>Many of us would then want to start using <strong>webpack</strong> to setup react application from scratch. <br>So, this is a good way to get started.</p><p>The steps would be as below :<br>a) Create a basic project and serve HTML.<br>b) Adding webpack to the project and bundle a simple JS file.<br>c) Adding Babel for ES6 support. <br>d) Adding React to the project.</p><h3>Step 1 : Basic setup</h3><p>Here we are going to create a basic project and add the html file. <br>To create the project and initialize the ‘package.json’ run the below commands:</p><pre>mkdir react-app-with-webpack<br>cd react-app-with-webpack<br>npm init -y</pre><p>Then, let’s add the main html file. We can add it inside anywhere but usually it is inside the <strong>‘public’ </strong>folder so let us add it under the same.</p><pre>mkdir public<br>cd public</pre><p><strong>‘index.html’ </strong>will contain basic HTML5 boilerplate:</p><pre>&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;React + Webpack&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Hello React + Webpack!&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Let’s check if this is running by serving this static html using npm<em> serve</em>.</p><pre>npx serve public</pre><p>Now if you navigate to <a href="http://localhost:3000">http://localhost:3000/</a>, you should be able to view the hello message we added in index.html file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_SB1taYn3DxUrEBoBWpGA.png" /></figure><h3>Step 2 : Adding Webpack</h3><p>Firstly, install webpack</p><pre>npm install webpack webpack-cli --save-dev</pre><p>Now we are going to create a simple javascript file (<strong>index.js</strong> inside <strong>“src”</strong> folder) which we will bundle using webpack.</p><pre>// src/index.js<br>const newH2Element = document.createElement(&#39;h2&#39;);<br>newH2Element.innerHTML = &#39;This heading is added via code&#39;;<br>document.body.append(newH2Element);</pre><p>Then, we need to configure webpack by creating it’s configuration file <strong>‘webpack.config.js’ </strong>in the root of the project.</p><pre>const path = require(&#39;path&#39;);<br><br>module.exports = {<br>    entry:&#39;./src/index.js&#39;,<br>    output : {<br>        filename: &#39;bundle.js&#39;,<br>        path: path.resolve(__dirname,&#39;build&#39;)<br>    }<br>}</pre><p>Here, <em>‘entry’</em> specifies which javascript file to bundle. And, <em>‘output’</em> specifies where should the bundled JS file be saved and the file name.</p><p>In <strong>‘package.json’</strong>, add the below script.</p><pre>//...<br>&quot;scripts&quot; : {<br>  &quot;build&quot;:&quot;webpack&quot;<br>},</pre><p>Now run <strong>‘npm run build’ </strong>in terminal. You would be able to see <strong>‘bundle.js’</strong> file inside a new folder <strong>‘build’</strong>!</p><p>Next step is to move the static assets to bundle. That is, we want to also include <strong>‘index.html’</strong> file in the<strong> ‘build’ </strong>folder.</p><p>Easiest way to do this is by using a plugin called HtmlWebpackPlugin.</p><pre>npm install html-webpack-plugin --save-dev</pre><p>Update the <strong>‘webpack.config.js’ </strong>as below :</p><pre>const path = require(&#39;path&#39;);<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);<br><br>module.exports = {<br>    entry:&#39;./src/index.js&#39;,<br>    output : {<br>        filename: &#39;bundle.js&#39;,<br>        path: path.resolve(__dirname,&#39;build&#39;)<br>    },<br>    plugins: [<br>        new HtmlWebpackPlugin({<br>            template: path.join(__dirname,&quot;public&quot;,&quot;index.html&quot;),<br>        })<br>    ]<br>}</pre><p>This will copy the <strong>public/index.html</strong> to <strong>‘build’</strong> folder and inject a link to the bundled JS (<strong>bundle.js</strong>).</p><p>Let’s try it out then!</p><pre>npm run build<br>npx serve build</pre><p>The <strong>‘index.html’</strong> in <strong>‘build’ </strong>folder has the <em>&lt;script defer=”defer” src=”bundle.js”&gt;&lt;/script&gt;</em> added now.</p><pre>&lt;!doctype html&gt;&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;UTF-8&quot;&gt;&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width,initial-scale=1&quot;&gt;&lt;title&gt;React + Webpack&lt;/title&gt;&lt;script defer=&quot;defer&quot; src=&quot;bundle.js&quot;&gt;&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Hello React + Webpack!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;</pre><p>And now you would be able to see the message <em>‘This heading is added via code’</em> added to the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4aIiGLej2An3vIcq-7YEQ.png" /></figure><p>So far we have used <strong>npx serve </strong>to check if everything works, but in actual scenarios we use <strong>‘webpack-dev-server’</strong>.</p><pre>npm install --save-dev webpack-dev-server</pre><p>Then it needs to be configured in ‘<strong>webpack.config.js’</strong></p><pre>//... <br>devServer : {<br>        static : {<br>            directory: path.join(__dirname,&#39;build&#39;),<br>        },<br>        port: 3000,<br>    },</pre><p>Now, add the script in <strong>‘package.json’</strong></p><pre>//...<br>&quot;scripts&quot; : {<br>  //...<br>  &quot;build&quot;: &quot;webpack --mode production&quot;,<br>  &quot;start&quot;: &quot;webpack serve --mode development&quot;,<br>},</pre><p>Check by running <strong>‘npm run start’ </strong>if app is still running as before.</p><h3>Step 3 : Adding Babel</h3><p>Why this is useful is because, using Babel we can keep using all ES6 features and Babel will take care to transpile it down to respective javascript versions that all browsers can understand (Here is an amazing article to read more on <a href="https://blog.jakoblind.no/babel-preset-env/">Babel</a> which is really helpful)</p><p>First step is to install the required packages.</p><pre>npm i @babel/core @babel/preset-env babel-loader --save-dev</pre><p>Next we need to tell webpack to pass the files through Babel when bundling (Add below config in <strong>‘webpack.config.js’</strong>) :</p><pre>//...<br>module : {<br>        //exclude node_modules<br>        rules : [<br>            {<br>                test : /\.(.js)$/,<br>                exclude: /node_modules/,<br>                use: [&quot;babel-loader&quot;],<br>            }<br>        ]<br>    },<br>    //pass all js files through Babel<br>    resolve: {<br>        extensions: [&quot;*&quot;,&quot;.js&quot;]<br>    }</pre><p>Now we need to create the .babelrc file, this is where we apply the ‘preset-env’ transform.</p><pre>// .babelrc<br><br>{<br>  &quot;presets&quot;: [<br>    &quot;@babel/preset-env&quot;<br>  ]<br>}</pre><p>Optionally, update index.js with some ES6 features which would not work without Babel (Honestly, most of them work without Babel in many browsers but for example IE browser does not support Array.fill)</p><pre>/ Use a feature that needs Babel to work in all browsers :)<br>// arrow functions + Array fill<br><br>const sayHelloXTimes = (times) =&gt; new Array(times).fill(1).map((a,i)=&gt;`Hello : ${i}`)<br><br>const newH2Element = document.createElement(&#39;h2&#39;);<br>newH2Element.innerHTML = sayHelloXTimes(10).join(`&lt;br/&gt;`);<br>document.body.append(newH2Element);</pre><p>Let’s check if it is working by running <strong>‘npm run start’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWUrs70xdKu3stxN82B8gw.png" /></figure><h3>Step 4 : Adding React</h3><p>Finally, we can add react now :)</p><p>First step is to install it.</p><pre>npm install react react-dom --save-dev<br>npm install @babel/preset-react --save-dev</pre><p>Then update the <strong>‘.babelrc’ </strong>file also to apply the<strong> ‘preset-react’ </strong>transform, which is needed to support JSX.</p><pre>// .babelrc<br><br>{<br>    &quot;presets&quot;: [<br>      &quot;@babel/preset-env&quot;,<br>      [&quot;@babel/preset-react&quot;, {<br>         &quot;runtime&quot;: &quot;automatic&quot;<br>      }]<br>    ]<br>}</pre><p>Note: specifying “runtime”:”automatic” enables a features of not needing to import React in all the files.</p><p>Also, we need to update <strong>webpack.config.js</strong> to pass ‘JSX’ through Babel.</p><pre>// webpack.config.js<br><br>{<br>  // ...,<br>  module: {<br>    // exclude node_modules<br>    rules: [<br>      {<br>        test: /\.(js|jsx)$/,         // &lt;-- added `|jsx` here<br>        exclude: /node_modules/,<br>        use: [&quot;babel-loader&quot;],<br>      },<br>    ],<br>  },<br>  // pass all js files through Babel<br>  resolve: {<br>    extensions: [&quot;*&quot;, &quot;.js&quot;, &quot;.jsx&quot;],    // &lt;-- added `.jsx` here<br>  },<br>}</pre><p>Let’s create a React component and add it inside index.js to see if eveything works.</p><pre>// src/Welcome.jsx<br><br>const Welcome = () =&gt; &lt;h3&gt;Welcome From React bundled using Webpack+Babel&lt;/h3&gt;<br><br>export default Welcome;</pre><pre>//--------------------------------------<br>//Using React<br>import { React } from &#39;react&#39;;<br>import { createRoot } from &#39;react-dom/client&#39;;<br><br>import Welcome from &#39;./Welcome&#39;;<br><br>const root = document.getElementById(&#39;root&#39;)<br>createRoot(root).render(&lt;Welcome/&gt;)</pre><p>We also need to create a <strong>root</strong> node in the <strong>index.html</strong> of the app.</p><pre>// index.html<br>// ......<br>&lt;body&gt;<br>    &lt;!-- &lt;h1&gt;Hello React + Webpack!&lt;/h1&gt; --&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>&lt;/body&gt;</pre><p>Now let’s execute<strong> ‘npm run start’</strong> to check if everything is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AWEPWkGGi-CR-heSWRI8g.png" /></figure><p>Voila! All good then.</p><p>You can also check that the app correctly runs in production, by running ‘<strong>npm run build’</strong> and then <strong>‘npx serve build’</strong></p><p>See the full code here : <a href="https://github.com/priyankajakob/react-webpack-setup">https://github.com/priyankajakob/react-webpack-setup</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a5e4f6f85d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>