<?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 Lawrence Eagles on Medium]]></title>
        <description><![CDATA[Stories by Lawrence Eagles on Medium]]></description>
        <link>https://medium.com/@eaglescoder?source=rss-9280a7128a92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*38kL84rGKe6JC_Hm</url>
            <title>Stories by Lawrence Eagles on Medium</title>
            <link>https://medium.com/@eaglescoder?source=rss-9280a7128a92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:39:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eaglescoder/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[How JavaScript Works: Understanding WebSockets in Nodejs with Socket.io]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-understanding-websockets-in-nodejs-with-socket-io-24bc9e584eed?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/24bc9e584eed</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 11:00:43 GMT</pubDate>
            <atom:updated>2023-04-11T13:06:05.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARIpv8jwSR7ojydKQP0BaA.png" /></figure><p>This is post # 72 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3>Introduction</h3><p>The WebSocket API enables us to establish bi-directional communication between a client — a browser and a server. And as a result, data can flow from client to server and server to client. Also, because WebSockets are always open, they allow real-time data flow in our application.</p><p>The first step of a WebSocket is for a client to send an HTTP request to the server — asking to open a connection. And if the server agrees, it will send a 101 Switching Protocols response— at which point the handshake is complete. So the TCP/IP connection is left open, thus, allowing a bi-direction flow of data between the server and the client with very low latency.</p><p>The WebSockets API allows several clients to connect to a server simultaneously. And this connection stays open until one of the parties drops off.</p><p>A typical application of the WebSockets API is a chat application, and the image below explains how this might work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/0*SS92rTcyKQfkrpE4" /></figure><p>From the image above, each client—user browser is connected via a Websocket to the chat application server. So when a user types a message and clicks send, the message gets sent down to the server via the WebSocket connection. And the server in turn sends the message up the Websockets to all the clients. Consequently, they get a notification and see the message. The point to note here is that these communications are real-time. And that means no extra user request or Ajax request is being made at any time.</p><p>The WebSockets API enables us to build real-time features by establishing a two-way connection — via a socket, between a client and a server. So WebSockets have a lot of applications in programming these include:</p><ul><li>Chat application</li><li>Multiplayer browser games</li><li>Streaming applications</li><li>Collaborative code editing software</li><li>Live text for sports/news websites</li><li>Real-time to-do apps with multiple users.</li><li>Online drawing canvas applications</li></ul><p>In this tutorial, we will learn more about WebSockets by building a chat application. And the prerequisites to gain the most from this article are outlined in the next section.</p><h3>Prerequisites</h3><p>To follow along in the article, the following are required:</p><ul><li>Basic knowledge of Nodejs</li><li>The latest version of Nodejs should be installed on your machine.</li><li>Basic knowledge of JavaScript</li></ul><h3>Getting started</h3><p>So to use the WebSockets API, we need some server code. And to get this we will build a Nodejs application.</p><p>Follow the steps below to bootstrap the Nodejs application:</p><ul><li>Create an application folder and from the folder initialize a Nodejs app by running the following code on your terminal:</li></ul><p>npm init -y</p><ul><li>Install the required packages by running:</li></ul><p>npm install express socket.io</p><p>And install dev-dependencies by running:</p><p>npm install -D nodemon</p><ul><li>Configure NPM Scripts by updating the scripts property in the package.json file as seen below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/376c44ee2d5d303a65cdc449a7ea027f/href">https://medium.com/media/376c44ee2d5d303a65cdc449a7ea027f/href</a></iframe><ul><li>Now, set up the express server by creating an src folder in the root directory. And in the src folder, create an index.js file with the following code:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e933c1b3d0204a390d7724d4691d0da3/href">https://medium.com/media/e933c1b3d0204a390d7724d4691d0da3/href</a></iframe><p>In the code above, we serve a static HTML file — the index.html file using the res.SendFile method. So whenever a user points the browser to <a href="http://localhost:5000/">http://localhost:5000/</a>, the index.html file is rendered to the browser. And we will create this index.html file in the next section.</p><p>Also, in the code above, we set up an express server and implemented socket.IO on the server. And we will learn more about this in the next section.</p><p>But for now, start the dev-server by running npm run dev and we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p6yYrJ7Pyu0Q7BiT" /></figure><p>So with our application bootstrapped, in the next section, we will focus on building the chat app properly.</p><h3>Building A Chat Application With WebSockets — Socket.IO</h3><p>To establish a socket connection between the browser and our Nodejs application, we will use a library called Socket.IO.</p><p>The Socket.IO library is used by installing it both on the client and the server. And it enables socket connection between the client and the server — thus, it enables real-time bidirectional event-based communication between the server and the client.</p><h4>Set up Socket.IO on the server</h4><p>In our current application setup, we have implemented Socket.IO on the server using the http.createrSever method from express.</p><p>When a client makes a connection with Socket.IO on the server, an event — called connection is fired. And in our current setup, Socket.IO listens for this event using the socket.on method.</p><p>And when the connection event fires, we call a callback and log made socket connection and the socket ID to the console.</p><p>This callback function takes a socket object as an argument. And this socket object refers to the instance of the socket made between the client and the server. So if ten different clients connect to the server, each client would have its socket instance.</p><h4>Set up Socket.IO on the client</h4><p>To set up Socket.IO on the client, create a pubic folder in the root directory. And in the public folder, create an index.html file with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3698d0184b64670b8592f1191343b69/href">https://medium.com/media/a3698d0184b64670b8592f1191343b69/href</a></iframe><p>And on the browser we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*82KHvdtqh_fRFM1T" /></figure><p>Now we need to set up Socket.IO. Add this line of code to the header section of the index.html file to load the socket.io-client:</p><p>&lt;script src=”/socket.io/socket.io.js”&gt;&lt;/script&gt;</p><p>The line of code above exposes an io global, the endpoint GET /socket.io/socket.io.js, and then connects.</p><p>Now to test if socket.io-client was loaded successfully, above the closing body tag, add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abab725e4e45d4bb1878a387eb5331aa/href">https://medium.com/media/abab725e4e45d4bb1878a387eb5331aa/href</a></iframe><p>And refresh the browser. We get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u2MOwaTFYvqemrgs" /></figure><p>From the image above, we see that made socket connection followed by the socket id is logged to the console confirming that a Websocket connect has been established between the server and the client.</p><p>Also, going forward our client-side JavaScript code will be written within these script tags above the body element.</p><h4>Emitting Messages With Socket.IO</h4><p>In the previous sub-sections, we set up Socket.IO on the client and the server. But in this section, we will work on emitting messages via sockets.</p><p>In our chat app, when we send data — a chat message from a browser, through a socket to the server, the server receives that message and emits data — the message to all the clients that are connected to it.</p><p>So to handle this when a user clicks the send button, we will emit an event from the client to the server via the created socket.</p><p>To implement this, we need to get all the necessary DOM elements by adding the following code below the // Query DOM comment in the index.html scripts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38704eed03ae2ef72e3dff4eb976ccac/href">https://medium.com/media/38704eed03ae2ef72e3dff4eb976ccac/href</a></iframe><p>Next, we add an event listener to the send button to listen for click events by adding the following code below the // Emit events comment in the index.html scripts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a01dda5aac01dd6165ffb102cbe6520c/href">https://medium.com/media/a01dda5aac01dd6165ffb102cbe6520c/href</a></iframe><p>In the code above, we added an event listener to the send button to listen for a click event. And when a click event occurs, the socket.emit is called in the event handler callback.</p><p>The socket.emit method takes two arguments: the name of the message — in this case, chat and an object that contains the message or data we are sending to the server.</p><p>So on the server, we will add an event listener to listen for this sent event. And to do this modify the io.on method in the index.js file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4134b85530bf82e275da65db0966947/href">https://medium.com/media/b4134b85530bf82e275da65db0966947/href</a></iframe><p>In the code above, we listen to the socket for the emission of the chat message by calling the socket.on method. And the socket.on method takes two arguments: the chat message and an event handler — callback.</p><p>Now we called io.sockets.emit method within the callback function to send this message out to all the clients connected to the server via a WebSocket. And this enables everyone in the chat room can see the message.</p><p>Note, io.sockets refers to all the WebSockets created by the different clients connected to the server. And io.sockets.emit(‘chat’, data) emits a message — the data from the client that sent the message, to all the connected clients — in the io.sockets collection.</p><p>Now with our current setup, a user can send a message from the client to our server. And the server, upon receiving the message, emits the chat message back to all sockets in the io.sockets collection. Thus, sending the message to all the connected clients.</p><p>Following this, on the client side, we need a way to display the received message on the browser. So add the following code below the // Listen for events comment in the script section in the index.html file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/969394607e3b5144c05795db3f4851ae/href">https://medium.com/media/969394607e3b5144c05795db3f4851ae/href</a></iframe><p>In the code above, socket.on listens for a chat message and calls a callback — an event handler upon receiving the chat message. And in the event handler, we added code that renders the message to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YxIyYY_bBzhaD1yT" /></figure><p>So with this, we have our basic chat functionality working. We can pass data from a client to a server and back from the server to all the clients connected via WebSocket.</p><h4>Broadcasting Messages</h4><p>In this section, we will use message broadcasting to notify other clients when a user is typing a message. And to implement this, add the following code below the // Broadcast feedback when user types comment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/228f396b8a46b53e083f96f59ba39360/href">https://medium.com/media/228f396b8a46b53e083f96f59ba39360/href</a></iframe><p>In the code above, we add an event listener that listens for a keypress event to the message input element. And when this event fires, we emit a typing event from the event handler by calling socket.emit — passing the user name as the data.</p><p>Now we need to handle this typing event on the server and to do this modify the io.connection method in the index.js file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d703ff22e9d0b1ed93d0d1cd07cb4a/href">https://medium.com/media/b0d703ff22e9d0b1ed93d0d1cd07cb4a/href</a></iframe><p>In the code above, we listen to the socket for a typing event. And once that event occurs we broadcast that event by calling socket.broadcast.emit. This emits a typing event and sends the received data to all connected client except the client that send the message.</p><p>Once again we need to handle this broadcasted message on the client side. And to do this, add the following code below the // Listen for typing message comment in the index.html scripts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf92c80ed2c9b67675bea5331454ff55/href">https://medium.com/media/cf92c80ed2c9b67675bea5331454ff55/href</a></iframe><p>From the code above, each client listens on their socket for a typing event.</p><p>Finally, update clear the feedback when the user finishes typing and clicks send. To this, modify the socket.on method below the // Listen for events comment as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35a14802505cc77c945927b991dcef64/href">https://medium.com/media/35a14802505cc77c945927b991dcef64/href</a></iframe><p>Now once the typing event is fired a message is printed to show that a user a typing as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wl1qPMBBRm8gYFXr" /></figure><h3>Conclusion</h3><p>In this article, we learned about the WebSocket API, a technology that enables a bidirectional flow of data between a server and a client with low latency.</p><p>And we worked with the Socket.IO library, a JavaScript library that makes it easy to set up WebSockets on the client and server.</p><p>If you are interested in the source code of the chat application we built, you can clone the repository on Github <a href="https://github.com/lawrenceagles/chat-app-websocket">here</a>.</p><p>Lastly, I hope after this tutorial you have learned enough to use WebSockets in your application.</p><p>WebSockets in JavaScript are very helpful, as they&#39;re more efficient than polling the server for data. But to properly use the WebSocket API and get an effective result, you need to understand how to implement WebSockets using lSocket.IO API or an alternative Websocket library like <a href="https://github.com/websockets/ws">WS</a>.</p><p>So even if you feel like the proper decisions have been made, it’s always necessary to verify that this is indeed true and your users have a great experience with your product.</p><p><a href="https://www.sessionstack.com/solutions/developers/">SessionStack</a> utilizes pub/sub-services to process all of the ingested behavioral data from the browser in real time. As the data is being ingested, SessionStack allows you to watch user sessions as videos, allowing you to see exactly what happened during their journey.</p><p>Combining this visual information with all of the tech data from the browser such as errors, stack traces, network issues, debug data, etc. you can easily understand problematic areas in your product and efficiently resolve them.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/solutions/developers/">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*H4IZju_66IO1gVJg" /></figure><p>SessionStack replaying a session</p><p>Interested in more about JavaScript? Check out all <a href="https://blog.sessionstack.com/how-javascript-works/home">“How JavaScript works” publications here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24bc9e584eed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-understanding-websockets-in-nodejs-with-socket-io-24bc9e584eed">How JavaScript Works: Understanding WebSockets in Nodejs with Socket.io</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript Works: A complete guide to asynchronous JavaScript]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-a-complete-guide-to-asynchronous-javascript-34ea34f8bd91?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ea34f8bd91</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[how-javascript-works]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Thu, 18 Aug 2022 15:49:43 GMT</pubDate>
            <atom:updated>2023-04-11T13:31:33.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-p1JgYMN8dwLzlsB5vEj0g.png" /></figure><p>This is post # 71 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-asynchronous">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3>Introduction</h3><p>Asynchronous JavaScript is one of the essential parts of the language because it governs how we handle long-running tasks — such as fetching data from a server or an API.</p><p>In a simplistic nutshell, we can look at asynchronous code as code that starts a task now and finishes it later. We will elaborate on this as we move on in the article but before then, let’s learn about synchronous code — the counterpart to asynchronous code.</p><p>JavaScript, by nature, is a synchronous language. And this means that JavaScript can execute only one code at a time — from top to bottom.</p><p>Consider the code below:</p><p>console.log(“logging line 1”);</p><p>console.log(“logging line 2”);</p><p>console.log(“logging line 3”);</p><p>By default, JavaScript executes the code above synchronously. And this means line by line. So line 1 cannot be executed before line 2, and line two cannot be executed before line 3.</p><p>Also, JavaScript is called a single-threaded language. And this essentially means the same thing as JavaScript being a synchronous language —by nature.</p><p>A thread is like an ordered sequence of statements as seen in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*89KzSPcamW9emgut" /></figure><p>In a thread, only one of those statements can run at a given time. And this is the crux of synchronous code: a single thread and one statement being executed at a time.</p><p>You can learn more about threads in <a href="https://blog.sessionstack.com/how-javascript-works-parallelism-vs-concurrency-in-javascript-whats-the-difference-99fc3602b9f5">our previous article in this series</a>.</p><p>So because in synchronous code, only one statement can run at a time, synchronous code is referred to as blocking code.</p><p>To elaborate on this, let us assume statement 2 in the image above is a long-running task such as a network request to a server. The result of this is that statements 3 and 4 cannot be executed until the execution of statement 2 is completed. Hence the synchronous code is referred to as “blocking code”.</p><p>Now, from our understanding of synchronous code, we see that if we have multiple statements — functions in a thread that perform long-running tasks, then the rest of the code below these functions is blocked from running until these functions complete their tasks.</p><p>This pattern can negatively affect the performance of our program. And this is where asynchronous code comes in.</p><p>As noted above, asynchronous code is code that starts a task now and finishes later. And by this, we mean when an asynchronous function that handles a long-running task is executed in a thread, the browser moves the long-running task away from that thread and continues processing it. Also, the browser simultaneously continues executing other functions in that thread but adds a callback function to the thread. Thus asynchronous code does not block the flow of execution — so they are referred to as non-blocking code.</p><p>When the long-running task is completed, a callback function is called when the other functions in the main thread finish executing. And this callback function handles the data returned from the long-running computation.</p><p>Consequently, the asynchronous programming pattern enables our program to start a long-running task and still continue the execution of other tasks in the thread. So we do not have to wait until that long-running task has finished.</p><p>Let‘s elaborate on this with some code examples.</p><p>Consider the synchronous code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3fe58187f291c6cb9bcb190a7dee5d4/href">https://medium.com/media/a3fe58187f291c6cb9bcb190a7dee5d4/href</a></iframe><p>Consider the asynchronous code example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad83e6f33cfe2cc633a8595cb5c421dc/href">https://medium.com/media/ad83e6f33cfe2cc633a8595cb5c421dc/href</a></iframe><p>In the code above, the synchronous code executed each statement sequentially. But in the asynchronous code example, the code execution was not sequential.</p><p>In the asynchronous code example, we used the setTimeout function to simulate a long-running task that takes two seconds to complete. Consequently, statement 2 is printed last to the console because the flow of execution is not blocked. Thus other statements were being executed.</p><p>Following this introduction, we will take a deep dive into asynchronous programming in JavaScript.</p><p>Let’s get started in the next section.</p><h3>Getting Started</h3><p>In the introduction, we worked with a small contrived example of asynchronous code. But in this section, we will go deeper by using network requests in place of setTimeout functions. And for this, we need to understand some concepts like HTTP requests.</p><h4>HTTP Requests</h4><p>Sometimes we want to show data such as blog posts, comments, a list of videos, or user data stored on a database or remote server on our website. And to get this data, we make HTTP requests to the external server or database.</p><p>HTTP requests are made to API endpoints — URLs exposed by APIs. And we interact with these endpoints to perform CRUD operations — reading, creating, updating, or deleting data.</p><p>In this article, we will work with endpoints from <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a>. And in the next section, we will learn about asynchronous programming patterns used to handle network requests in JavaScript.</p><h3>Asynchronous programming patterns</h3><p>Asynchronous programming patterns in JavaScript have evolved with the language. And in this section, we will learn how asynchronous functions have historically been implemented in JavaScript. We will learn about asynchronous programming patterns such as callbacks, Promises, and the Async-await.</p><p>Also, we will learn about making a network request with the XMLHTTPRequest object and the Fetch API.</p><h4>Making HTTP Requests With The XMLHttpRequest Object</h4><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> object is an asynchronous API that enables us to make a network request to an endpoint or database. The XMLHttpRequest API is an old asynchronous JavaScript pattern that uses events.</p><p>Event handlers are a form of asynchronous programming — where the event is the asynchronous or long-running task, and the event handler is the function that is called when the event occurs.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61955cb0fde95441ee914e9d378139c8/href">https://medium.com/media/61955cb0fde95441ee914e9d378139c8/href</a></iframe><p>prints a list of posts as seen in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1X57-sifnLU60Fl" /></figure><p>Note, to use the code above in a Nodejs environment you will need to install a package such as <a href="https://www.npmjs.com/package/xmlhttprequest">node-XMLHttpRequest</a>.</p><p>In our example above, the XMLHttpRequest object uses an event listener that listens for the readystatechange event. And when this event fires, the event handler is called to handle the event. You can learn all you need to know about events and event handlers by reading our previous article in this series <a href="https://blog.sessionstack.com/how-javascript-works-a-complete-guide-to-events-and-event-listeners-in-javascript-e0abe5c3ae55?source=collection_category---5------3-----------------------">here</a>.</p><h4>Asynchronous programming With Callbacks</h4><p>In the code above, whenever we reuse the getPosts function, we print the fetched posts to the console. However, we can make further computations with the result of the getPosts functions by using several asynchronous programming patterns. And the first pattern we will learn about is the callback pattern.</p><p>A callback function is a first-class function passed as an argument to another function — — with the expectation that the callback will be called when an asynchronous task gets completed.</p><p>An event handler is a form of a callback function. And in this section, we will learn how to enhance our code using callbacks.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0165c913ba2cc69f73ed3be89cacb258/href">https://medium.com/media/0165c913ba2cc69f73ed3be89cacb258/href</a></iframe><p>In the code above, we modified the getPosts function to use a callback. Consequently, we can call the callback to handle the different results of the network request — if it is successful or if there is an error.</p><p>Also, whenever we reuse the getPosts function, we can pass a different callback to it. Thus we have made our code more reusable and more flexible.</p><p><strong>Callback Hell</strong></p><p>So we have seen that the callback pattern helps make our code more reusable and flexible. But when we need to make several network requests sequentially, the callback pattern can quickly become messy and hard to maintain.</p><p>But before we elaborate on this, let’s refactor our getPosts function as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30b86ce9fb6e563fc5239033e3c7ec31/href">https://medium.com/media/30b86ce9fb6e563fc5239033e3c7ec31/href</a></iframe><p>In the code above, we made the resource URL dynamic by passing the resource argument as the first parameter to the getPosts function. Thus when we call the getPosts function, we can dynamically pass any URL we want.</p><p>Now, if we are to make the network requests we mentioned above, we will end up with deeply nested callbacks as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41e75c0a18fa7d0238240beb2b0fcc83/href">https://medium.com/media/41e75c0a18fa7d0238240beb2b0fcc83/href</a></iframe><p>Things even can get worse as we nest more callbacks within callbacks. And this is referred to as callback hell. Callback hell is the drawback to the callback pattern.</p><p>To resolve callback hell, we use modern asynchronous JavaScript patterns such as promises or async-await.</p><p>Let’s learn about Promises in the next section.</p><h4>Asynchronous programming With Promises</h4><p>Promises are the foundations of modern asynchronous JavaScript, and promises are either resolved or rejected.</p><p>When an asynchronous function implements the Promise API, the function returns a promise object — often before the operation finishes. The promise object contains information about the current state of the operation and methods to handle its eventual success or failure.</p><p>To implement the promise API, we use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise">Promise constructor</a> in an asynchronous function, as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c1db95ae75cf0d4da9fd2cb3f22df0/href">https://medium.com/media/32c1db95ae75cf0d4da9fd2cb3f22df0/href</a></iframe><p>In the example above, the Promise constructor takes a function — where the network request is made, as an argument. And this function takes two arguments: the resolve and the reject function.</p><p>The resolve function is called to resolve the promise if the request is successful, and the reject function is called if the request fails.</p><p>Now, when we call the asyncFunc function, it returns a promise object. So to work with this function, we call the then method — to work the returned data if the promise resolves and the catch method to handle the error if the promise is rejected.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef172f8a1ce821f83f6d0299f28de2a8/href">https://medium.com/media/ef172f8a1ce821f83f6d0299f28de2a8/href</a></iframe><p>With this knowledge let’s refactor our getPosts function to use the promise API.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cff9ffd8508f99507171e910f054406a/href">https://medium.com/media/cff9ffd8508f99507171e910f054406a/href</a></iframe><p>The code above implements the Promises API, and we see that instead of calling callbacks in the event handler, we called the resolve function if the request is successful and the reject function if the request fails.</p><p><strong>Chaining Promises</strong></p><p>We have already seen how we chain promises by calling the .then and .catch methods. Chaining promises is very useful, especially in cases that can result in callback hell — where we need to fetch data sequentially as mentioned in a previous section.</p><p>Chaining promises together enable us to perform asynchronous tasks one after another in a clean way. To elaborate on this, we will implement the callback hell example using Promise API.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1e011179c7a82c438058b62ecd53e19/href">https://medium.com/media/a1e011179c7a82c438058b62ecd53e19/href</a></iframe><p>Note, the catch method in the promises above catches any error no matter the number of nested requests. Also, chaining promises, as seen above, gives us a cleaner and more maintainable way to make multiple network requests sequentially.</p><h3>The Native Fetch API</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch">Fetch API</a> is a fairly modern API for making HTTP requests in JavaScript, but it has many enhancements over the XMLHttpRequest object. Also, the Fetch API implements the promise API under the hood, and its syntax requires much less code, so it is easier to use.</p><p>The Fetch API is simply a function that takes a resource — an endpoint as its argument and returns a promise. Consequently, we can call .then and .catch methods to handle the cases where the promise is resolved and rejected.</p><p>We can implement our example using the Fetch API as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3edf3e2fc8d7e7b4b07489c0185dd26b/href">https://medium.com/media/3edf3e2fc8d7e7b4b07489c0185dd26b/href</a></iframe><p>Note, in the code above, response.json() returns a promise so we leverage promise chaining to handle it.</p><p>Also, in a Nodejs environment, you will need to install a package such as <a href="https://github.com/node-fetch/node-fetch">node-fetch</a> to work with the Fetch API.</p><h4>Asynchronous programming With Async Await</h4><p>The async and await keywords are recently introduced to JavaScript. And they enable us to chain promises together in a clean and much more readable way.</p><p>While the Promise API has a lot of improvements over callbacks, it can still get messy as we chain multiple promises together.</p><p>But with async-await, we can separate all asynchronous code into an asynchronous function and use the await keyword inside to chain promises together in a more readable way.</p><p>We can make a function asynchronous by adding the async keyword in front of it. Then we can use the await keyword inside that function to chain promises.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06ab50e09cd21d5a7b2a7db81244e313/href">https://medium.com/media/06ab50e09cd21d5a7b2a7db81244e313/href</a></iframe><p>In the code above, we refactored the getPosts function from using the Promise API to async-await. And we can see that this is cleaner and more readable.</p><p>Also, the await keyword stops JavaScript from assigning a value to the response and data variables until the promise is resolved.</p><p>The power of the await keyword is that we can chain multiple promises sequentially within the asynchronous function, and the code is still non-blocking. So this is a cleaner, more readable, and maintainable way to handle promises compared to using the .then method.</p><p><strong>Error Handling</strong></p><p>When we implement the Promise API, we handle errors by calling the .catch method. However, in the async-await pattern, there is no such method available. So to handle errors when using the async-await keyword, we implement the async-await inside a try…catch block as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2672ad7b409ce998db439e85425abc38/href">https://medium.com/media/2672ad7b409ce998db439e85425abc38/href</a></iframe><p>So in the code above, JavaScript executes the code in the try block and invokes the getPosts function. And if the promise is resolved, the JSON data is logged to the console. But if the promise is rejected, the code in the catch blocks runs. When the code in the catch block runs, the catch function receives the thrown error object as an argument and handles the error.</p><h3>Conclusion</h3><p>In this article, we have learned about asynchronous JavaScript. And how the patterns have evolved historically from callbacks to Promises to async-await. Also, we learned about the native Fetch API which is the modern javascript API for making a network request.</p><p>After going through this article, I do hope that you understand how asynchronous JavaScript works under the hood — even when you use high-level APIs like the Fetch API or the async-await pattern.</p><p>So although we all like to apply new technologies, upgrading our code — to modern APIs should be complemented with proper testing. And even if we feel we’ve tested everything before release it’s always necessary to verify that our users have a great experience with our product.</p><p>A solution like <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-asynchronous">SessionStack</a> allows us to replay customer journeys as videos, showing how our customers actually experience our product. We can quickly determine whether our product is performing according to their expectations or not. In case we see that something is wrong, we can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that we can easily understand the problem and resolve it. We can co-browse with users, segment them based on their behavior, analyze user journeys, and unlock new growth opportunities for our applications.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-asynchronous">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*PxNuK1IdAH7FHek7" /></figure><p>SessionStack replaying a session</p><p>Interested in more about JavaScript? Check out all <a href="https://blog.sessionstack.com/how-javascript-works/home">“How JavaScript works” publications here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ea34f8bd91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-a-complete-guide-to-asynchronous-javascript-34ea34f8bd91">How JavaScript Works: A complete guide to asynchronous JavaScript</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript Works: Understanding modular and functional programming with JavaScript and Firebase…]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-understanding-modular-and-functional-programming-with-javascript-and-firebase-1354e890ec94?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/1354e890ec94</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 14:05:04 GMT</pubDate>
            <atom:updated>2023-04-11T13:04:07.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>How JavaScript Works: Understanding modular and functional programming with JavaScript and Firebase 9</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkmYxJrblxnbVcUexZjXXQ.png" /></figure><p>This is post # 70 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-modular-programming">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3>Introduction</h3><p>Firebase is a backend-as-a-service (BAAS) platform that provides back-end services such as database, authentication, file storage, cloud functions, hosting, etc. And Firebase provides simple APIs that front-end and mobile developers can consume to plug these services into their applications.</p><p>Also, Firebase handles all the server-side logic and heavy lifting so that front-end and mobile developers do not go through the hassle of setting up a custom-backed infrastructure.</p><p>So, Firebase is an efficient alternative to setting up custom back-end infrastructure using tools like MongoDB, Mongoose, Node, and Express. Thus, Firebase enables front-end and mobile developers to focus on their areas of expertise. And consequently, it is loved by front-end and mobile developers.</p><p>In this article, we will learn about modular and functional programming by working with Firebase 9.</p><p>Compared to Firebase 8, Firebase 9 adopts a modular and functional approach, enabling us to import only the Firebase functions we need in our project. And we can also optimize our code with tree-shaking by using module bundlers like Wepback and Rollup.</p><p>So, using Firebase 9 in this functional way means more optimized output code and smaller file size. And we will learn more about this in action in a subsequent section as we build our application.</p><h3>Scaffolding the client-side JavaScript application</h3><p>Our app will be built with plain JavaSript, HTML, and Tailwind CSS. And we will bundle the app with Webpack.</p><p>We will get started by scaffolding our JavaScript application using NPM. In your terminal, run the following code from your project directory:</p><p>npm init -y</p><p>Now install your app’s dependencies and dev dependencies by running:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c91fd6d0ad5a1dcb2d8b987dda249293/href">https://medium.com/media/c91fd6d0ad5a1dcb2d8b987dda249293/href</a></iframe><p>Next, we enable ES module and setup up our NPM scripts by adding ”type”: “module” to the package.json properties. And also updating the script property of the package.json file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dad000cb60a503fcce0bc446814c04d8/href">https://medium.com/media/dad000cb60a503fcce0bc446814c04d8/href</a></iframe><p>By installing all the dependencies and dev-dependencies in the previous step, we have installed Webpack, Tailwind CSS, and Firebase. Now let’s configure each of them.</p><h4>Configure Webpack</h4><p>To configure Webpack create a webpack.config.js file in the root directory and add the following code to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aea6ca4137407a701e5348f82dc322ca/href">https://medium.com/media/aea6ca4137407a701e5348f82dc322ca/href</a></iframe><h4>Configure Tailwind CSS</h4><p>To configure Tailwind CSS, run: npx tailwindcss init -p in the terminal to create a tailwind.config.js file and a postcss.config.js file — since we are adding Tailwind with postCSS. Note because we enabled ES module in our application, there will be some compatibility issues with the tailwind.config.js and the postcss.config.js files because these files use CommonJS module. So to solve this, change the extension of both files to .cjs. Now replace the content of the tailwind.config.cjs file with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/076534b60b7d1dbbc3f70f8bf55a3369/href">https://medium.com/media/076534b60b7d1dbbc3f70f8bf55a3369/href</a></iframe><p>Next, we add the app’s entry point and HTML boilerplate. To do this, create a src directory in the root directory. And create an index.js file and an index.html file inside the src directory.</p><p>Add the following code to the index.html file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6184a30dbafb5862893e2c87db21116/href">https://medium.com/media/c6184a30dbafb5862893e2c87db21116/href</a></iframe><p>Also, in the src directory, create a main.css file and add the Tailwind CSS code below:</p><p>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</p><p>Note in the boilerplate above, we are linking to the bundled JavaScript and CSS file.</p><p>To test our application we need to first bundle it by running:</p><p>npm run build</p><p>Now open another terminal and run:</p><p>npm start</p><p>And we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GDtwmh4eldFCFj45" /></figure><h3>Building A Book Application</h3><p>To build the book application we will start by configuring Firebase and synchronizing our client app with the Firebase project.</p><h4>Configure Firebase</h4><p>In this section, we will learn how to configure firebase and build our application backend. I have created a well-commented boilerplate to initialize Firebase. Add the following code to the `index.js` file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd9a60c208434a0e31c625ed56ce40c6/href">https://medium.com/media/dd9a60c208434a0e31c625ed56ce40c6/href</a></iframe><p>In the above, we initialize the app using the initializeApp function. The initializeApp function takes the firebaseConfig object as an argument and uses it to connect our JavaScript app to our Firebase back-end.</p><p>Also, we connected our app to a firebase database using the getFirestore function and we imported all the functions we need from firestore. We will learn more about these functions later in this section.</p><p>Now we need to create a Firebase project, a database, and configure an app. Creating a Firebase project will give us a config object that enables us to connect our app to your Firebase project resource.</p><p>To create a new Firebase project, follow the steps below:</p><ol><li>visit<a href="https://console.firebase.google.com/u/0/"> console.firebase.google.com/</a> and click on <strong>Add project</strong>. And you get:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XhlSkHG7YpKPt6iZ" /></figure><p>2. Enter your project name and click <strong>continue</strong>.</p><p>3. You can optionally enable Google analytics for your project.</p><p>4. Click on <strong>create project.</strong> And when Firebase finishes creating your project, click on <strong>continue</strong> to go to the project’s console.</p><p>Now you need to register an app with your project. To do this, follow the steps below:</p><ol><li>Click the Web icon &lt;/&gt; on the project console to launch the setup workflow as seen below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RLV4Ud8_kOLeEByV" /></figure><p>2. Add your app’s nickname and click on <strong>Register app</strong>.</p><p>2. Copy the config object code provided for you and update the config object in the index.js file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea50a6142159c8b537e9c3b61bfd5ded/href">https://medium.com/media/ea50a6142159c8b537e9c3b61bfd5ded/href</a></iframe><p>The next step is to set up a database and connect to that database from the JavaScript application. To do this, follow the steps below:</p><ol><li>On the sidebar of your Firebase console, click on <strong>Firestore Database</strong></li><li>Click on <strong>Create database</strong> and select start in <strong>test-mode</strong> and click <strong>Next</strong></li><li>Select firestore location and click on <strong>Enable</strong> to create a database</li></ol><p>The Firebase database consists of collections and documents.</p><p>And a collection here refers to a collection of certain data-type. So since we are creating a book store application, we will name the collection books because it is a collection of a data type called book.</p><p>Click on <strong>start collection</strong> and you get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0g0OFbmqRpSKYIhD" /></figure><p>Type books as the collection ID, then click on <strong>Next</strong>.</p><p>Now you get a form to add new documents — as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fpwhn7TNlj3mYNc4" /></figure><p>Firebase documents consist of document ID, fields, data-type, and value.</p><p>Create a document with the code below:</p><p>{<br> title: “JavaScript The Good Parts”,<br> author: “Douglas Crockford”<br>}</p><p>In Firebase, the fields are the properties. So in the field input, add title. And in the value input, add “JavaScript The Good Parts”. Then click on <strong>Add field</strong> and add the author field and its value.</p><p>Also, click on <strong>Auto-ID</strong> to generate an ID and click on <strong>save</strong>. You can later add other books by following this pattern.</p><p>The next step is to connect this database to your JavaScript application and get data from the books collection. And to do this, we need to import the three functions from the firestore part of the Firebase library.</p><h3>Fetch And Render Data</h3><p>In this sub-section, we will learn how to fetch data from our Firebase database and render them in the UI. To this, create a utils folder in the src directory and add these files to the utils folder: createElem.js, renderBooks.js, and index.js.</p><p>In the createElem.js file, add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/053d3d88a29d627fcc11793db2282e60/href">https://medium.com/media/053d3d88a29d627fcc11793db2282e60/href</a></iframe><p>And in the renderBooks.js file, add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfa2584a424bdcda300f30bb28989f63/href">https://medium.com/media/cfa2584a424bdcda300f30bb28989f63/href</a></iframe><p>Lastly, in the index.js file, add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b4551ce9a2c5d75d44ce0b6c20693a/href">https://medium.com/media/48b4551ce9a2c5d75d44ce0b6c20693a/href</a></iframe><p>The createElem function is a helper function that enables us to create HTML elements using JavaScript. And the renderBooks function renders a list of books using the createElem function.</p><p>Now import the renderBooks function to our index.js file below the comment:</p><p>// import UI rendering logic.</p><p>To render our data to the view, we will subscribe to the book collection by using the firestore <a href="https://firebase.google.com/docs/firestore/query-data/listen">collection</a> function. And this function enables us to actively listen to the book collection and update the UI automatically whenever things change.</p><p>The collection function takes a collection reference as its first argument. And we can get a reference to the books collection by adding this line of code to the index.js file — below the // Ref collection comment:</p><p>const colRef = collection(db, ‘books’);</p><p>Now we subscribe to the books collection by adding the code below to the index.js file — below the // getRealtime data comment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6eef08a1105dcab86b53effc67643f1/href">https://medium.com/media/a6eef08a1105dcab86b53effc67643f1/href</a></iframe><p>In the code above, the getSnapshot function takes a callback function as its second argument. And this callback function receives a snapshot of the books collection as its argument and invokes the renderBooks function — passing the books array as an argument.</p><p>Thus when the books collection changes, the renderBooks is invoked, and the UI is updated automatically.</p><p>To check if we are successfully fetching data from firebase, run the build script and start the server, and we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cWmtM5SiYp09jGnJ" /></figure><h3>Deleting Data</h3><p>To delete data, we use the <a href="https://firebase.google.com/docs/firestore/manage-data/delete-data">delete</a> function. And this function takes two arguments:</p><ul><li>A document reference is gotten by using the doc function</li><li>A Callback function.</li></ul><p>We will use event delegation to listen for click events on a book title. And once this occurs, we call the delete function passing the document reference as its argument.</p><p>To do this, add the following code below in the index.js file in the src directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d45ddd97db4323bc6390428dcf0b565e/href">https://medium.com/media/d45ddd97db4323bc6390428dcf0b565e/href</a></iframe><p>In the renderBooks function, we added the id for each book by using the <a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes">HTML 5 data attribute</a>. So we can easily get the clicked book by using: event.target.dataset.id in our listener.</p><p>Now when we click on a book, it gets deleted automatically.</p><h3>Creating and Updating Data</h3><p>To create documents, we will use addDoc function, and to update a document, we will use the updateDoc function. And to implement the add document and update document features, we will add event listeners that listens for a submit event in both the add-book form and the update-book form. So once the submit event occurs, the appropriate function is invoked to handle the event.</p><p>To implement this, add the following code to the index.js file in the src directory, to get the DOM elements of the forms:</p><p>const addForm = document.querySelector(‘#add-book’);</p><p>const updateForm = document.querySelector(‘#update-book’);</p><p>Below the // Handle add new document comment, add the following code to add an event listener to the add-form form:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfb8618e5c6c4ec5b156169f6b17dece/href">https://medium.com/media/dfb8618e5c6c4ec5b156169f6b17dece/href</a></iframe><p>Also, below the // Handle update document comment, add the following code to add an event listener to the update-form form:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c92256cbddd6c405cd2f2a16c7da33d/href">https://medium.com/media/8c92256cbddd6c405cd2f2a16c7da33d/href</a></iframe><p>Now run the build script and start the dev server. The app is complete, and all CRUD operations work correctly. In the next section, we will deploy our app using firebase hosting.</p><h3>Hosting The Book Store Application</h3><p><a href="https://firebase.google.com/docs/hosting/quickstart">Firebase Hosting</a> is straightforward to use and set up. To host our application follow the steps below:</p><ol><li>First, install the <a href="https://firebase.google.com/docs/cli#mac-linux-npm">Firebase CLI</a> by running the code below: <br>npm install -g firebase-tools</li><li>Log in and list your projects with the code below:</li></ol><p>// login<br>firebase login</p><p>// list projects<br> firebase projects:list</p><p>And we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r_dzT5OCOtdimtZ2" /></figure><p>3. Connect the local project to a Firebase project by running:</p><p>firebase init hosting</p><p>Now from the on-screen instruction, select use an existing project and choose a Firebase project.</p><p>Next, specify a public directory — in this case, it is the dist directory.</p><p>And configure the app as a single-page application.</p><p>Firebase would automatically add rewrite configurations for you.</p><p>Also, at the end of the configuration, Firebase will create some files: firebase.json file,firebaserc in the root directory, and an index.html file in the dist folder.</p><p>But this does not contain our application markup. To fix this, delete the contents of the index.html file created by Firebase — — in the dist folder. And copy the contents of the index.html file in the src directory into the index.html file in the dist folder.</p><p>Then update the link to the CSS and JS files as seen below:</p><p>// Link to CSS<br>&lt;link href=”main.css” rel=”stylesheet”&gt;</p><p>// Link to JS<br>&lt;script type=”module” src=”bundle.js”&gt;&lt;/script&gt;</p><p>Before we deploy the app, run:</p><p>firebase deploy — only hosting</p><p>And when the deployment is complete, Firebase gives you a hosting url. And you can access the app using this url.</p><h3>Conclusion</h3><p>In this article, we have learned about Firebase base the backend as a service platform. And by building and developing the book application with Firebase 9, we learned how to build a modular application using functional programming.</p><p>Lastly, if you are interested in the source code of the book store application, you can get it on <a href="https://github.com/lawrenceagles/book-store-firebase-9">Github</a>.</p><p>So although the functional programming paradigm enables us to build modular applications and leverage optimization techniques such as tree-shaking, it should be complemented with proper testing. And even if we feel we’ve tested everything before the release it is always necessary to verify that our users have a great experience with our product.</p><p>A solution like <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-modular-programming">SessionStack</a> allows us to replay customer journeys as videos, showing us how our customers actually experience our product. We can quickly determine whether our product is performing according to their expectations or not. In case we see that something is wrong, we can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that we can easily understand the problem and resolve it. We can co-browse with users, segment them based on their behavior, analyze user journeys, and unlock new growth opportunities for our applications.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-modular-programming">give SessionStack a try.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*NiR6cZdWpqit0QX5" /></figure><p>SessionStack replaying a session</p><p>Interested in more about JavaScript? Check out all <a href="https://blog.sessionstack.com/how-javascript-works/home">“How JavaScript works” publications here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1354e890ec94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-understanding-modular-and-functional-programming-with-javascript-and-firebase-1354e890ec94">How JavaScript Works: Understanding modular and functional programming with JavaScript and Firebase…</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: A complete guide to Events And Event Listeners in JavaScript]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-a-complete-guide-to-events-and-event-listeners-in-javascript-e0abe5c3ae55?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0abe5c3ae55</guid>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[event-handlers]]></category>
            <category><![CDATA[event-listener]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 14:17:58 GMT</pubDate>
            <atom:updated>2023-04-11T12:58:58.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bd5_0cAIJozvERIe" /></figure><p>This is post # 67 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-events">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3>Introduction</h3><p>Events are signals or actions fired or emitted by systems we interact with programmatically. And these signals are picked up and handled by event listeners — code sections that listen and respond to events.</p><p>Events are emitted to notify our programs of changes that can affect executions. And these changes can be due to user interactions such as mouse movements, button clicks, etc.</p><p>In JavaScript, an emitted event is represented by an event object that contains methods and properties or information about the event. And this event object is passed as an argument to any event listener listening to the event.</p><p>Some of the properties and methods of the event object are:</p><ul><li>isTrusted</li><li>bubbles</li><li>cancelBubble</li><li>currentTarget</li><li>defaultPrevented</li><li>srcElement</li><li>target</li><li>timeStamp</li><li>type</li><li>stopPropagation</li><li>preventDefault</li><li>stopImmedaitePropagation</li><li>initEvent</li></ul><p>There are different types of events in JavaScript, and an event can originate as a result of user interaction or programmatically from our code.</p><p>The term event interface refers to events that occur in the DOM, and these events have a name that ends in Event. Examples of these events are:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent">AnimationEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent">CloseEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent">CustomEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent">DeviceMotionEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent">DeviceOrientationEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/DragEvent">DragEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent">FocusEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/FormDataEvent">FormDataEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/InputEvent">InputEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent">KeyboardEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent">MessageEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent">MouseEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent">ProgressEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent">SubmitEvent</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent">TouchEvent</a></li></ul><h3>Emitting And Handling Events</h3><p>In JavaScript, DOM events that are generated programmatically are called synthetic events.</p><p>And in this section, we will learn how to create and handle events programmatically.</p><h4>How to create Events</h4><p>Events are created by invoking the Event constructor as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f9071f3e79a0e7ea84d009cb06342ec/href">https://medium.com/media/5f9071f3e79a0e7ea84d009cb06342ec/href</a></iframe><p>The code above creates a greet event and returns an event object — with type: “greet”. But this greet event object does not do anything on its own. We need to add some code that listens for the emission of this event and responds to it.</p><h4>How to Handle Events</h4><p>In JavaScript, we listen to events with Event listeners or Event handlers.</p><p>So to add a listener to the greet event above, we will use the addEventListener method as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0291c01c91e1bfce75397f6febea23c8/href">https://medium.com/media/0291c01c91e1bfce75397f6febea23c8/href</a></iframe><p>In the code above, we invoked the addEventListener method on the eventTarget. The eventTarget here refers to an object e.g the Document or the window object, as well as any parent or child element that can receive events and have listeners for them.</p><p>We will learn more about this later. So the code above listens for the emission of a greet event on the eventTarget.</p><p>However, we still need to notify all listeners when this event is fired. And to do this, we use the dispatchEvent(event) as seen below:</p><p>eventTarget.dispatchEvent(event);</p><p>The dispatchEvent(event) method takes the event object as an argument and dispatches it. And once this event is emitted the dispatchEvent(event) invokes all the associated listeners synchronously, thereby triggering a response.</p><p>Our final code should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a33b3cc4a84dd923e6dd55d9df9efc17/href">https://medium.com/media/a33b3cc4a84dd923e6dd55d9df9efc17/href</a></iframe><p>To elaborate on this, we will use real elements as the eventTarget as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b45b2794b0bb73ace80741726270d678/href">https://medium.com/media/b45b2794b0bb73ace80741726270d678/href</a></iframe><p>The code above is similar to our previous example. But here, we used the querySelector method to get a reference to the eventTarget — the DOM element with id=”greet”. And we stored this reference on the elem variable used throughout the code. The result is the same as the previous example, with a small addition introduced with the line:</p><p>elem.innerHTML = “Greetings from John Doe!”</p><p>And this prints “Greetings from John Doe!” on the browser once the event fires. You can see this in action <a href="https://codepen.io/Lawrenceagles/pen/mdxyqzy">here</a>.</p><p>Note the terms event listeners and event handlers are loosely used to refer to the same thing. But in the strict sense event listeners refers to code used to add a listener to an event target:</p><p>eventTarget.addEventListener(‘click’, function() { /* do stuff here*/ }, false);</p><p>While an event handler refers to the handler function invoked once the listener is notified of an emitted event. Following this, several event listeners can use the same handlers as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07c36e798631d6d26a3e8238b677ffa5/href">https://medium.com/media/07c36e798631d6d26a3e8238b677ffa5/href</a></iframe><p>In the code above, we created an event handler — handleLogDetails and used it in all the event listeners. Also, we used the CustomEvent constructor that enables us to create events with additional information. And these extra pieces of information are logged to the console.</p><p>You can see this in action <a href="https://codepen.io/Lawrenceagles/pen/MWVYOLQ">here</a>.</p><p>In addition to adding event listeners to event targets, we can also programmatically remove event listeners by using the removeEventListener method as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/693df2cd4ab4a29de9c86f89d24e77e0/href">https://medium.com/media/693df2cd4ab4a29de9c86f89d24e77e0/href</a></iframe><h3>Event Delegation</h3><p>So far, we have learned about adding event listeners to a single element. But what happens if we want to listen to events emitted from many child elements? Event delegation gives us a clean and efficient pattern that enables us to add one listener to a parent element. And this event listener will listen for and analyze bubbled events on each child element.</p><p>Event delegation utilizes event bubbling, so before we learn how to implement event delegation, let’s learn about event bubbling.</p><h4>Event Bubbling And Capture</h4><p>Event bubbling, target, and capture are 3 phases of an event flow in the browser. They describe how browsers handle events fired from nested elements.</p><p>During the bubbling phase, an event fired on a child element bubbles up the DOM tree. And this event can be captured and handled by any event listener on its ancestor element — outer elements.</p><p>An event only bubbles if the bubble boolean property is true.</p><p>During the bubbling phase, the browser starts looking for listeners from the immediate parent of the child element from which the event is fired. The browser then continues its search up the DOM tree.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/595ed598581224ce33bc339e6b176f65/href">https://medium.com/media/595ed598581224ce33bc339e6b176f65/href</a></iframe><p>The code above demonstrates event bubbling. And we see that when the button is clicked the event bubbles up the DOM. Consequently, the event listeners of all its ancestor elements are notified of the click event, and they log their responses to the console.</p><p>You can see this in action <a href="https://codepen.io/Lawrenceagles/pen/XWEJVry">here</a>.</p><p>The capture phase is the reverse of the bubble phase. In the capture phase, the browser starts searching for listeners from the outermost ancestor element — the html element and searches down the DOM tree until it reaches the direct parent of the child element that emitted the event.</p><p>Lastly, in the target phase, the browser checks to see if the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/target">event target </a>has an event listener for the fired event. And after this, it propagates the event to the immediate parent element and continues propagating it up the DOM tree until it reaches its outermost ancestor element. Note the browser will only propagate an event up the DOM tree if the bubbles property of the emitted event is true.</p><p>We can determine which phase of the event flow is currently being executed programmatically from the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase">eventPhase</a> property.</p><p>By default, JavaScript events go through the capturing and target phases. But an event only enters the bubbling phase if the bubbles property is true. Also, all event listeners are by default registered in the bubbling phase. And if you want to register an event for the capturing phase, you can set the optional third property of the addEventListener method to true.</p><h4>Stop Propagation</h4><p>Event bubbling may not be a desirable effect in some scenarios. And in such cases, we can prevent the event from propagating by invoking the stopPropagation method on the event object. So by invoking the stopPropagation method in our previous example, we can prevent the bubbling of the current event up the DOM tree. To do this, modify the JavaScript code snippet in the example above, as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b51c84a83cebc6fd6cbc5943dd9ee1b6/href">https://medium.com/media/b51c84a83cebc6fd6cbc5943dd9ee1b6/href</a></iframe><p>The stopPropagation method does not prevent any default behavior like reloading a form once it is submitted, and clicking on links will still work. But to prevent default behaviors, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault">preventDefault</a> method.</p><p>Also, if multiple event listeners are listening for that event, invoking the stopPropagation method will not prevent the event from propagating to those listeners. But to do this, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation">preventImmediatePropagation</a> method.</p><p>Now with our understanding of event bubbling, we can learn how to implement event delegation.</p><p>As mentioned above, event delegation enables us to utilize event bubbling in a useful way. To see this in action, consider a webpage with the following HTML:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d078263cf4c7af0ed66141416945b8b/href">https://medium.com/media/1d078263cf4c7af0ed66141416945b8b/href</a></iframe><p>In the code above, the section element has five children. And each child element has a name attribute added to it using HTML 5<a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes"> data-*</a> global attributes. Our task is to log the name attribute on a child element to the console when that child element is clicked.</p><p>So rather than, adding an event listener to each child element, we can leverage event delegation and rely on event bubbling to propagate the event up the DOM tree. And by doing this, we only need to add one listener to the outermost element in the DOM tree, as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/432fe0d2ff6099958f64f5e92a58774e/href">https://medium.com/media/432fe0d2ff6099958f64f5e92a58774e/href</a></iframe><p>In the code above, we added the event listener to the document, so any event that is emitted from any element in the DOM tree will be captured and handled by our listener.</p><p>Thus the code above prints the name attribute of the clicked child element to the console. And you can see this in action <a href="https://codepen.io/Lawrenceagles/pen/WNzbXQr">here</a>.</p><p>We can see from our implementation of event delegation that event delegation gives us a clean and efficient way to handle events originating from nested elements.</p><h3>Conclusion</h3><p>In this article, we have learned about events in JavaScript, and how to create and handle them.</p><p>We also learned about event delegation — a pattern that enables us to utilize event bubbling or event propagation in a useful way.</p><p>And in cases where event propagation is not needed, we learned how to stop the event from propagating.</p><p>JavaScript events are very important to us these days because they lay the foundation for useful patterns such as the observer pattern and the publish-subscribe pattern.</p><p><a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-events">SessionStack</a> utilizes pub/sub-services to process all of the ingested behavioral data from the browser in real-time. As the data is being ingested, SessionStack allows you to watch user sessions as videos, allowing you to see exactly what happened during their journey.</p><p>Combining this visual information with all of the tech data from the browser such as errors, stack traces, network issues, debug data, etc. you can easily understand problematic areas in your product and efficiently resolve them.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-events">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*VlpXNCWco-leR2wj" /><figcaption>SessionStack replaying a session</figcaption></figure><p>Interested in more about JavaScript? Check out all <a href="https://blog.sessionstack.com/how-javascript-works/home">“How JavaScript works” publications here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0abe5c3ae55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-a-complete-guide-to-events-and-event-listeners-in-javascript-e0abe5c3ae55">How JavaScript works: A complete guide to Events And Event Listeners in JavaScript</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: understanding Snowpack, the next generation JavaScript bundler]]></title>
            <link>https://medium.com/sessionstack-blog/understanding-snowpack-the-next-generation-javascript-bundler-c541a3efe54d?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/c541a3efe54d</guid>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[bundler]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[snowpack]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Tue, 31 May 2022 15:51:47 GMT</pubDate>
            <atom:updated>2023-04-11T14:11:31.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUGrVXu6SvU6YKjtY7iTSQ.png" /></figure><p>Post # 64 of the series How Javascript Works is dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-snowpack">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3>Introduction</h3><p>According to the documentation, <a href="https://www.snowpack.dev/">Snowpack</a> is a lightning-fast frontend build tool, designed for the modern web. It is an alternative to heavier, more complex bundlers like Webpack or Parcel in your development workflow.</p><p>Traditional bundle-based bundlers like Webpack and Rollup bundles all our application files and assets before serving them via the dev-server. And this process is repeated when we update and save the file. The result of this is slow dev-server startup time that decreases linearly as our application size increases.</p><p>Snowpack takes a different approach. And by leveraging native <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">JavaScript modules — ESM</a>, Snowpack eliminates unnecessary work and stays fast regardless of the application size. Bundlers that utilize ESM are called ESM-bundlers and another good alternative is <a href="https://vitejs.dev/">Vite</a> which we have covered in a <a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-vite-965bdd8ffb42">previous article in this series</a>.</p><p>Also, Snowpack implements a novel concept known as unbundled development. An idea that involves serving our application unbundled during development. And according to the official documentation, Snowpack’s unbundled web development server starts up in 50ms or less and stays fast in large projects. We will learn more about Snowpack’s unbundled development in the next section.</p><p>Snowpack is extensible via plugins and it supports Hot module refresh — HMR out of the box. Unlike <a href="https://webpack.js.org/">Webpack</a>, Snowpack simplifies development by providing built-in support for JSX, TypeScript, React, Preact, CSS Modules, <a href="https://www.snowpack.dev/reference/supported-files">and more.</a> And this removes the need of installing and configuring loaders.</p><p>In the next section, we will get started with Snowpack by learning about the files it supports in detail.</p><h3>Getting Started With Snowpack</h3><p>In this section, we will take a deeper look at Snowpack and learn about some of its key features.</p><h4>Supported Files</h4><p>Out of the box, Snowpack supports a lot of file types:</p><ul><li>JavaScript — .js and .mjs files<br>Snowpack leverages the native JavaScript module system — ESM.<br>Since ESM is supported by most browsers, Snowpack can import code directly to the browser during development. And this is what makes Snowpack’s unbundled development workflow possible.</li><li>TypeScript — .ts and .tsx files<br>Although snowpack does not support type-checking out of the box, it provides built-in support to build TypeScript files into JavaScript. However, type-checking can be added via the <a href="https://www.npmjs.com/package/@snowpack/plugin-typescript">@snowpack/plugin-typescript</a> plugin.</li><li>JSX — .jsx and .tsx files<br>Snowpack provides built-in support to build JSX files — .jsx and .tsx to JavaScript. But it does not support JSX in .js and .ts files by default. To add this feature, you can build your JavaScript using the <a href="https://www.npmjs.com/package/@snowpack/plugin-babel">@snowpack/plugin-babel</a> plugin. This plugin gives full compiler customization via Babel.</li><li>Also, if you are using Preact, Snowpack will automatically detect this and switch to using the Preact-style JSX h() function.</li><li>CSS — .css files<br>Snowpack allows you to import CSS files directly into your application. But it provides support for compile-to-CSS languages like Sass &amp; Less via plugins.</li></ul><p>CSS Modules — .module.css<br>Snowpack supports CSS modules using the [name].module.css naming convention.<br>CSS Modules export a special styles object by default. And this object maps your original classnames to unique identifiers. And importing a CSS module will automatically apply that CSS to the page.</p><ul><li>Images &amp; Assets — .svg, .jpg, .png, etc.<br>Snowpack enables importing all assets via ESM import. And this returns a URL reference to the final built asset, enabling us to reference non-JS assets by URL.<br>An example is creating an image element with an src attribute pointing to that image.</li><li>WebAssembly — .wasm<br>Snowpack supports loading WebAssembly — WASM files directly into your application via the browser’s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly">WebAssembly</a> API. And you can learn more about this from the <a href="https://www.snowpack.dev/guides/wasm">WebAssembly guide</a>.</li><li>JSON — .json<br>Snowpacks support importing JSON files directly into your application. And in default import the full JSON object is returned.</li></ul><p>Using these file types does not require a loader or custom configuration. And we can extend Snowpack to support more languages by implementing the methods specified in the <a href="https://www.snowpack.dev/guides/connecting-tools">tooling guide</a>.</p><h4>Unbundled Development</h4><p>Popular bundle-based build tools like Webpack and Rollup build applications using the bundled development pattern. The bundled development pattern involves bundling all the application files and assets before they are served. And on every save, the entire application is re-bundled even if only a single file was updated.</p><p>Running the whole application through a bundler on every save adds additional work and makes the dev workflow unnecessarily complex.</p><p>Snowpack uses a novel idea called unbundled development. The unbundled development pattern involves serving the unbundled — individual application files to the browser. These files can still be built using tools like Babel, TypeScript, and SASS and then loaded with their dependencies into the browser using ESM import and export. And when a file changes, Snowpack rebuilds only that file.</p><p>This single file builds on every update — in the unbundled development is faster, predictable, easy to configure &amp; debug, and deterministic.</p><p>Also, in the unbundled development pattern, every file is built individually and cached indefinitely. So your dev environment will only build a file once, and your browser will never download a file twice — until it changes. This is the real power of unbundled development.</p><p>The image below compares the bundled development pattern with the unbundled development pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DjHkbPFX3SafMh8I" /></figure><p>It is important to note that the unbundled development pattern supports traditional bundlers for building your application for production. So when you bundle for production, you can plug in your favorite bundler via an official Snowpack plugin e.g the Snowpack plugin for Webpack.</p><p>Consequently, Snowpack gives you the best of both worlds: fast, unbundled development with optimized performance in your bundled production builds.</p><p>When compared to the bundled development pattern, the unbundled development pattern has the following advantages:</p><ul><li>Single-file builds are fast.</li><li>Single-file builds are deterministic.</li><li>Single-file builds are easier to debug.</li><li>Project size doesn’t affect dev speed.</li><li>Individual files cache better.</li></ul><h4>The DevServer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jeMCKaH24qryfsvc" /></figure><p>Snowpack dev-server only builds files requested by the browser. And the result of this is that Snowpack can startup instantly. In contrast, there is always a time lag of about 30+ sec with the dev-servers of traditional bundlers.</p><p>Also, with the unbundled development pattern, Snowpack can scale to infinitely large projects without slowing down.</p><h4>The Build pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ngaU-iB0NW0LZ3Z_" /></figure><p>The build your application for production, Snowpack uses the command snowpack build. And running this command tells Snowpack to generate a static production build of your site.</p><p>Note one of Snowpack’s design principles is: <strong>You should be able to use a bundler because you want to, and not because you need to.</strong></p><p>So Snowpack treats bundling as optional production optimization, that you can skip over until you need it.</p><p>By default running the snowpack build command builds your application using the unbundled approach. However, this lacks some performance optimization. And you can get this by leveraging your favorite traditional bundler via plugins like the <a href="https://www.npmjs.com/package/@snowpack/plugin-webpack">@snowpack/plugin-webpack</a> and <a href="https://github.com/ParamagicDev/snowpack-plugin-rollup-bundle">snowpack-plugin-rollup-bundle</a>.</p><p>Integrating these bundles is a seamless process. And it requires no configuration because Snowpack builds your application before sending it to the bundler. So the bundler’s only job is to build HTML, CSS, and JS.</p><h4>Snowpack.config.js File</h4><p>This is a config object that holds the configuration used to customize the behavior of Snowpack.</p><p>To generate this file run the command: snowpack init as seen below:</p><p>The snowpack.config.js file supports many options, and we will learn about some of them as we build our application in a subsequent section. But you can get more details about these options <a href="https://www.snowpack.dev/reference/configuration">here</a>.</p><h3>Setting Up a Snowpack Project</h3><p>The easiest way to bootstrap a Snowpack project is to use the <a href="https://github.com/FredKSchott/snowpack/tree/main/create-snowpack-app/cli">Create-Snowpack App</a> — CSA CLI tool.</p><p>The Creat Snowpack App command has the following format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/745643d7e26fa12763e378cd7b3461e0/href">https://medium.com/media/745643d7e26fa12763e378cd7b3461e0/href</a></iframe><p>The command above allows you to specify an app-folder-name, an app-template-NAME, a package manager such as yarn, and more.</p><p>And Snowpack provides both official and community templates for different frameworks and libraries.</p><h4>Bootstrap Application and Install Dependencies</h4><p>To bootstrap a Snowpack application, run the following command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d127b204e3d37bd79dbaf32268867a7d/href">https://medium.com/media/d127b204e3d37bd79dbaf32268867a7d/href</a></iframe><p>And start the dev server with the following command:</p><p>cd react-snowpack <br>npm run start</p><p>And we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JB79BaTGHAHF2i2n" /></figure><p>Now, we install React and React Dom by running:</p><p>npm install react react-dom — save</p><h4>Customize project structure</h4><p>Since we are adding a bunch of files let’s structure the application properly. In the root directory, create an src and a public directory.</p><p>Now move the index.css file and index.html file to the public directory. Then rename the index.js file to index.jsx and move it into the src directory. You can do all these via the CLI by running the following commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3284e60040c8789e42f4cccfd2b724e4/href">https://medium.com/media/3284e60040c8789e42f4cccfd2b724e4/href</a></iframe><p>Structuring your like this Snowpack since the files are in different places. But you can solve this by customizing the snowpack.config.js file. Relace the mount option in the snowpack.config.js file with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fb624eb6c6266753f7371b418012379/href">https://medium.com/media/2fb624eb6c6266753f7371b418012379/href</a></iframe><p>Note the mount configuration changes where Snowpack looks for and builds files.</p><p>Since Snowpack builds files in src directory, like src/index.js into /dist/index.js, you’ll need to change that path in your index.html. We also, you’ll need to add a div with id=”root” for React-Dom. So update the body element in the index.html file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f338b89283276ac777fae537e6b32f2/href">https://medium.com/media/6f338b89283276ac777fae537e6b32f2/href</a></iframe><h4>Creating Components</h4><p>Now we need to create our application components. In the src directory create an App.jsx component containing the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8877610c5663b95a56ac43d395366f6c/href">https://medium.com/media/8877610c5663b95a56ac43d395366f6c/href</a></iframe><p>Also, create a folder called components in the src directory. And in the components folder create a Counter.jsx component and a Counter.module.css file.</p><p>Add the following code to the Counter.jsx component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1def229cd5286af88cf635a4ac70dab/href">https://medium.com/media/e1def229cd5286af88cf635a4ac70dab/href</a></iframe><p>And add the following styles to the Counter.module.css file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c570ca0b3fefa8f6c6829ebf08c193d2/href">https://medium.com/media/c570ca0b3fefa8f6c6829ebf08c193d2/href</a></iframe><h4>Updating Render</h4><p>Now replace the code in the index.jsx with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f8593614dde7d66d814e205d5ce0f2/href">https://medium.com/media/c1f8593614dde7d66d814e205d5ce0f2/href</a></iframe><p>Finally, build your application by running:</p><p>npm run build</p><p>And start the dev-server by running:</p><p>npm start</p><p>And we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IF2Ql7oebfhkDh8Y" /></figure><h4>Customizing Snowpack With Plugins</h4><p>We can enhance and customize Snowpack via plugins. And in this section, we will use the <a href="http://snowpack/plugin-sass">Snowpack SASS plugin</a> to add support for SASS. To do this, install the plugin by running:</p><p>npm i @snowpack/plugin-sass</p><p>Now, update the plugin property of the snowpack.config.js file as seen below:</p><p>plugins: [‘@snowpack/plugin-sass’],</p><p>Then rename the Counter.module.css to Counter.module.scss and also update the import as seen below:</p><p>import styles from &quot;./Counter.module.scss&quot;</p><p>Build your application and start the dev server. And we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y_x1rIw3t_MqSg5H" /></figure><p>So everything works fine.</p><h3>Conclusion</h3><p>Snowpack is a next-generation JavaScript bundler that simplifies and speeds up development and the build process. And with the novel and revolutionary unbundled development principle Snowpack is one of the pioneers of ESM-bundlers. And many of the awesome features of Vite are inspired by Snowpack.</p><p>In this article, we have learned a lot about Snowpack. And I hope you will give it a try in your next front-end project.</p><p>ESM bundlers like Snowpack make it much easier for software to have efficient and high-performing code. And since we all like to apply new technologies &amp; upgrade our code so even if we feel we’ve tested everything before release, it’s always necessary to verify that our users have a great experience with our product.</p><p>A solution like <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-snowpack">SessionStack</a> allows us to replay customer journeys as videos, showing us how our customers actually experience our product. We can quickly determine whether our product is performing according to their expectations or not. In case we see that something is wrong, we can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that we can easily understand the problem and resolve it. We can co-browse with users, segment them based on their behavior, analyze user journeys, and unlock new growth opportunities for our applications.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-snowpack">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*EAQegALuwKaaKWky" /></figure><p>SessionStack replaying a session</p><p>Interested in more about JavaScript? Check out all <a href="https://blog.sessionstack.com/how-javascript-works/home">“How JavaScript works” publications here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c541a3efe54d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/understanding-snowpack-the-next-generation-javascript-bundler-c541a3efe54d">How JavaScript works: understanding Snowpack, the next generation JavaScript bundler</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: A deep dive into esbuild]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-a-deep-dive-into-esbuild-5d997f93a8b4?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d997f93a8b4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[esbuild]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bundler]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Thu, 12 May 2022 08:33:34 GMT</pubDate>
            <atom:updated>2023-04-11T13:02:51.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ov450Ufuu5TGwM0AdtysA.png" /></figure><p>This is post #62 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-esbuild">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3><strong>Introduction</strong></h3><p><a href="https://esbuild.github.io/">Esbuild</a> is a blazing fast JavaScript bundler built with Golang. Esbuild is a next-generation JavaScript bundler aimed at improving build tool performance and ease of use. And some of its main features are:</p><ul><li>Extreme speed without needing a cache</li><li>ES6 and CommonJS modules</li><li>Tree shaking of ES6 modules</li><li>An <a href="https://esbuild.github.io/api/">API</a> for JavaScript and Go</li><li><a href="https://esbuild.github.io/content-types/#typescript">TypeScript</a> and <a href="https://esbuild.github.io/content-types/#jsx">JSX</a> syntax</li><li><a href="https://esbuild.github.io/api/#sourcemap">Source maps</a></li><li><a href="https://esbuild.github.io/api/#minify">Minification</a></li><li><a href="https://esbuild.github.io/plugins/">Plugins</a></li></ul><p>Although esbuild does not have a robust feature-set like Webpack, it does its job well — it is easy to use and blazing fast. The image below shows a performance comparison between esbuild and other leading JavaScript bundlers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*xWW-OIn-CnQnt5jp" /></figure><p>According to esbuild’s official website, the above image shows the time to do a production bundle of 10 copies of the <a href="https://github.com/mrdoob/three.js">three.js</a> library from scratch using default settings, including minification and source maps. More info <a href="https://esbuild.github.io/faq/#benchmark-details">here</a>.</p><p>We can see from the image above that it took esbuild 0.33 seconds to perform this task, and Webpack 5 took 41.53 seconds to perform this task.</p><p>While esbuild outperforms other JavaScript bundlers, it is important to mention a downside. And this is because performance is a tradeoff, so while esbuid is lightning-fast, it is not as feature-packed as Webpack.</p><p>Also, esbuild has not reached version 1.0, and although esbuild is rising in popularity, it is still less popular than other established bundlers like Webpack and Rollup, as seen in the npm trend below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SzOnIsAi6sojaGVb" /></figure><p>However, esbuild’s minimal feature set means it is not as complex as Webpack. esbuild is simple to learn and use, and it is blazing fast.</p><p>In addition to the caveats above, esbuild provides APIs for JavaScript, CLI, and Golang.</p><p>And in this article, we will learn about esbuild and how to bundle JavaScript applications with it.</p><p>Let’s get started in the next section.</p><h3><strong>Getting Started</strong></h3><p>Before delving into code, we will learn some esbuild concepts such as the esbuild content types and build API.</p><h4><strong>Content Types</strong></h4><p>Esbuild provides built-in support for different content types using loaders. These loaders are similar to Webpack loaders in functionality — they tell esbuild how to parse each content type. Some of these loaders: the TypeScript loader, the JavaScript loader, and the CSS loader are configured by default. And this means esbuild provides out-of-the-box support for these content types.</p><p>Below is a list of the content types supported by esbuild:</p><ul><li>Javascript: The JavaScript loader is enabled by default for .js, .cjs, and .mjs files.</li><li>TypeScript: The TypeScript loader is enabled by default for .ts, .tsx, .mts, and .cts files. And this enables esbuild to provide built-in support for parsing TypeScript syntax and discarding the type annotations. However, esbuild does not perform type-checking.</li><li>JSX: The JSX loader is enabled by default for .jsx and .tsx files. However, JSX syntax is not enabled in .js files by default. But we can enable configure this using the build API as seen below:<br><a href="https://gist.github.com/lawrenceagles/2d53816f6c58b6c34d6e17d0eb0a897e">https://gist.github.com/lawrenceagles/2d53816f6c58b6c34d6e17d0eb0a897e</a></li></ul><p>We will learn more about the esbuild build API in a subsequent section.</p><ul><li>JSON: This loader parses JSON files into JavaScript objects and exports that object by default. It is also enabled by default for .json files.</li><li>CSS: In esbuild, CSS is first-class content-type and this means esbuild can bundle CSS files directly without needing to import your CSS from JavaScript code. As seen below:<br><a href="https://gist.github.com/lawrenceagles/2a394cf3da5780a2f558df37a24ca889">https://gist.github.com/lawrenceagles/2a394cf3da5780a2f558df37a24ca889</a></li></ul><p>So this loader is enabled by default for .css files and it loads these files as CSS syntax.</p><ul><li>Text: This leader is enabled by default for .txt files. The text loader loads the file as a string at build time and exports the string as the default export. And it provides a simple API as seen below<br><a href="https://gist.github.com/lawrenceagles/bd9b8189dbb08e3d65476fb4e0410a8e">https://gist.github.com/lawrenceagles/bd9b8189dbb08e3d65476fb4e0410a8e</a></li><li>Binary: This loader loads the file as a binary buffer at build time and embeds it into the bundle using Base64 encoding. However, this loader is not enabled by default.</li><li>Base64: This loader loads the file as a binary buffer at build time and embeds it into the bundle as a string using Base64 encoding. This loader is also not enabled by default.</li><li>Data URL: This loader loads the file as a binary buffer at build time and embeds it into the bundle as a Base64-encoded data URL. The data URL loader is useful for bundling images and it can be used in tandem with the CSS loader to load images using url().</li><li>This loader is not enabled by default. And to use it, we need to configure it for the appropriate file extension, as seen below:<br><a href="https://gist.github.com/lawrenceagles/71dbee9cd7393515f8db283db005c75a">https://gist.github.com/lawrenceagles/71dbee9cd7393515f8db283db005c75a</a></li><li>External file: This loader copies files to the output directory and embeds the file name into the bundle as a string. And this string is exported using the default export. Similar to the data URL loader this loader can be used to load images and can work together with the CSS loader.</li><li>To use this loader we need to manually configure it for the appropriate extension, as seen below:<br><a href="https://gist.github.com/lawrenceagles/6c1121af845829b4f8875af454a244eb">https://gist.github.com/lawrenceagles/6c1121af845829b4f8875af454a244eb</a><br>And using it looks like this:<br><a href="https://gist.github.com/lawrenceagles/b568cc5c02930a16d7bd39528782907a">https://gist.github.com/lawrenceagles/b568cc5c02930a16d7bd39528782907a</a></li></ul><h3><strong>The Build API</strong></h3><p>Although we can use esbuild via the terminal using the CLI API, if to pass many options to the CLI it can become unwieldy. So for more sophisticated use cases, esbuild also provides a JavaScript API that is the build API. And this allows us to customize the behavior of esbuild. It is synonymous with the webpack.config.js file for Webpack.</p><p>To esbuild build API looks something like this:<br><a href="https://gist.github.com/lawrenceagles/8be4b1bd951e0b433daf804d3d825d2a">https://gist.github.com/lawrenceagles/8be4b1bd951e0b433daf804d3d825d2a</a></p><p>The build function runs the esbuild executable in a child process and returns a promise that resolves when the build is complete.</p><p>Although esbuild provides an alternative build API: buildSync — that runs synchronously it is best to use the async build API because esbuild plugins only work with the asynchronous API.</p><p>In an advanced case where we want to support old browsers, we need to transform modern JavaScript syntax into older JavaScript syntax.</p><p>We can configure the target environment as seen below:<br><a href="https://gist.github.com/lawrenceagles/aeca2ca9bcf7869ab92dbd872b9f0c4a">https://gist.github.com/lawrenceagles/aeca2ca9bcf7869ab92dbd872b9f0c4a</a></p><p>Note the example above uses the buildSync API.</p><p>The esbuild build API provides us with many simple and advanced options for customizing the behavior of esbuild.</p><p>And in the code above, we have used some of these options:</p><ul><li>Entry points: This option is an array of files. And each file serves as an input to the bundling algorithm. They are called entry points because they are evaluated first, then they load all other code in the app.<br>So instead of loading many libraries on your page with &lt;script&gt; tags, we can use the import statements to add them to our app’s entry point.</li><li>Outfile: This option is only applicable if there is only a single entry point as seen in our example above. The outfile option specifies the name of the final bundle — the output file created by the build process.</li><li>When there are multiple entry points, we must use the outdir option to specify an output directory.</li><li>Outdir: This option specifies an output directory for the build process. And this directory will be created only if it does not already exist. For example, the code below would create an output directory called output for the build operation:<br><a href="https://gist.github.com/lawrenceagles/fea875722e3b92874c71516bc78be45d">https://gist.github.com/lawrenceagles/fea875722e3b92874c71516bc78be45d</a></li><li>Bundle: esbuild does not bundle by default, so to bundle our file we need to explicitly specify it as seen above by setting its option to true.</li><li>Minify: When set to true this option enables the minification of our code during the build process. Minified code is smaller than pretty-printed codes, and they are easier to download. But minified code is more difficult to debug, so usually, we minify code when we are building for production.</li><li>Sourcemap: A sourcemap is a file that provides a way to map minified and uglified JavaScript bundle into its unbundled state. During the built state application assets — CSS &amp; JavaScript files get minified and combined into a single bundle to make delivering them from the server more efficient. However, these minified and uglified bundles are difficult to read and debug. Sourcemaps is a file that maps from the bundled source code to the original — unbundled source code thus enabling the browser to reconstruct the unbundled source and deliver it in the debugger. By setting this option to true we tell esbuild to generate sourcemaps.</li><li>Target: This specifies the target environment — like the browser, for the bundled JavaScript and/or CSS code. So if the JavaScript syntax is too new for the specified environment, it tells esbuild to transform it into older JavaScript syntax that can work in these environments.</li></ul><p>Apart from these, there are more <a href="https://esbuild.github.io/api/#simple-options">options</a> like watch, serve, and other <a href="https://esbuild.github.io/api/#advanced-options">advanced options</a> such as <a href="https://esbuild.github.io/api/#tree-shaking">tree shaking</a>, <a href="https://esbuild.github.io/api/#jsx-fragment">JSX fragments</a>, <a href="https://esbuild.github.io/api/#jsx-factory">JSX factory</a>, etc.</p><h3><strong>Bundling with esbuild</strong></h3><p>In this section, we will learn how to bundle applications with esbuild.</p><p>To use esbuild, first, create a nodejs project by running:</p><p>npm init -y</p><p>From your project directory. Then install the esbuild package by running:</p><p>npm install esbuild</p><p>You can verify the version by running:</p><p>/node_modules/.bin/esbuild — version</p><p>And this prints: 0.14.38</p><p>We will be bundling a React application so install the following React packages:</p><p>npm install react react-dom</p><p>Now create an app.jsx file containing the following code:<br><a href="https://gist.github.com/lawrenceagles/4829768fab37f3839874610d6504c97a">https://gist.github.com/lawrenceagles/4829768fab37f3839874610d6504c97a</a></p><p>Now we can tell esbuild to bundle our application using the CLI API by running:</p><p>./node_modules/.bin/esbuild app.jsx — bundle — outfile=bundle.js</p><p>And we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*31CQCcFY-O-yJcag" /></figure><p>So by running the command above, esbuild bundles our app into a bundle.js file. Also, esbuild converts the JSX syntax to JavaScript without any configuration other than the .jsx extension.</p><p>There are two things to note from our example above:</p><ol><li>The esbuild build process does not bundle our app by default, so we explicitly need to pass the — bundle flag in the command. And where the <br>— bundle flag is absent, esbuild would run the <a href="https://esbuild.github.io/api/#transform-api">Transformation API </a>instead of the build API.<br>The esbuild transformation API is ideal for environments such as the browser — that don’t have a file system because it performs operations on a single string without access to the file system. And in the case above, by running: <br>./node_modules/.bin/esbuild app.jsx — outfile=bundle.js<br>The transformation API is called because the — bundle flag is absent, and our code is transformed into a bundle.js file with the following code:<br><a href="https://gist.github.com/lawrenceagles/ca983900b7189d075cd807654594fb2e">https://gist.github.com/lawrenceagles/ca983900b7189d075cd807654594fb2e</a><br>Thus we can see that the transformation API transformed our JSX syntax into pure JavaScript.</li><li>The second thing to note is that by default, esbuild does not allow JSX syntax in .js files, so we had to name our file app.jsx. But if we rename our app.jsx file to app.js and try to build or transform our app we get an error as seen below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*858nr9uqdSz7annZ" /></figure><p>And while this can be fixed by adding the loader flag: — loader:.js=jsx to the CLI command, we can also do this using the build API.</p><p>So rename the app.jsx file to app.js and create a buid.js file containing the following codes:<br><a href="https://gist.github.com/lawrenceagles/1c71b91cd981df752d430db3391b4be5">https://gist.github.com/lawrenceagles/1c71b91cd981df752d430db3391b4be5</a></p><p>Then update the package.json script as seen below:<br><a href="https://gist.github.com/lawrenceagles/7981b3be6b5b7dac04fbe9d11fc26490">https://gist.github.com/lawrenceagles/7981b3be6b5b7dac04fbe9d11fc26490</a></p><p>Now we can build our app by running:<br>npm run build</p><p>Also, setting the bundle option to false tells esbuild to use the transformation API instead of the build API.</p><h3><strong>Plugins</strong></h3><p>Esbuild <a href="https://esbuild.github.io/plugins/">plugins</a> enable developers to hook into the build process and perform operations. And unlike the build API and the Transformation API, the esbuild plugin API is not available from the CLI. Thus you can only use them via the build API.</p><p>And it is important to keep in mind that esbuild plugins do not work with the buildSync API as mentioned above.</p><p>One drawback with using the plugin API is that it is not mature. And accounting for the documentation:<br>“The plugin API is new and still experimental. It may change in the future before version 1.0.0 of esbuild as new use cases are uncovered. You can follow <a href="https://github.com/evanw/esbuild/issues/111">the tracking issue</a> for updates about this feature.”</p><p>With this in mind, various plugins are developed by the community, but these are not officially supported. <a href="https://github.com/esbuild/community-plugins">Here is a list of these plugins.</a></p><h3><strong>Conclusion</strong></h3><p>In the article, we have learned a lot about esbuild the next-generation and blazing fast JavaScript bundler.</p><p>Esbuild is minimal featurewise if compared to bundlers like Webpack. However, it trades these features for optimal performance. So this should be the key thing to consider before adopting esbuild.</p><p>But this is resolved by using a package like <a href="https://vitejs.dev/">Vite</a>. Vite is a feature-rich Webpack alternative. Vite uses esbuild under the hood — in a smart way. And if you are new to Vite, you can learn all about Vite in our <a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-vite-965bdd8ffb42?source=collection_home---4------0-----------------------">previous article in this series</a>.</p><p>Blazing-fast next-generation JavaScript bundlers like esbuild make it much easier for software to have efficient and high-performing code. esbuild has not reached version 1.0 and its API is still evolving. But since we all like to apply new technologies &amp; upgrade our code so even if we feel we’ve tested everything before release, it’s always necessary to verify that our users have a great experience with our product.</p><p>A solution like<a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-esbuild"> SessionStack</a> allows us to replay customer journeys as videos, showing us how our customers actually experience our product. We can quickly determine whether our product is performing according to their expectations or not. In case we see that something is wrong, we can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that we can easily understand the problem and resolve it. We can co-browse with users, segment them based on their behavior, analyze user journeys, and unlock new growth opportunities for our applications.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-esbuild">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*r1V7fIyNnyC41Tez" /><figcaption>SessionStack replaying a session</figcaption></figure><p>If you missed the previous chapters of the series, you can find them here:</p><ul><li><a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf?source=collection_home---2------1----------------">An overview of the engine, the runtime, and the call stack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e?source=collection_home---2------2----------------">Inside Google’s V8 engine + 5 tips on how to write optimized code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec?source=collection_home---2------0----------------">Memory management + how to handle 4 common memory leaks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">The event loop and the rise of Async programming + 5 ways to better coding with async/await</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-websockets-and-http-2-with-sse-how-to-pick-the-right-path-584e6b8e3bf7?source=collection_home---4------0----------------">Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79">A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">The building blocks of Web Workers + 5 cases when you should use them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service Workers, their life-cycle, and use case</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-mechanics-of-web-push-notifications-290176c5c55d">The mechanics of Web Push Notifications</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401">Tracking changes in the DOM using MutationObserver</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">The rendering engine and tips to optimize its performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-networking-layer-how-to-optimize-its-performance-and-security-f71b7414d34c">Inside the Networking Layer + How to Optimize Its Performance and Security</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-css-and-js-animations-how-to-optimize-their-performance-db0e79586216">Under the hood of CSS and JS animations + how to optimize their performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8">Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-classes-and-inheritance-transpiling-in-babel-and-113612cdc220">The internals of classes and inheritance + transpiling in Babel and TypeScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-storage-engines-how-to-choose-the-proper-storage-api-da50879ef576">Storage engines + how to choose the proper storage API</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">The internals of Shadow DOM + how to build self-contained components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-webrtc-and-the-mechanics-of-peer-to-peer-connectivity-87cc56c1d0ab">WebRTC and the mechanics of peer to peer connectivity</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-custom-elements-best-practices-on-building-reusable-e118e888de0c">Under the hood of custom elements + Best practices on building reusable components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-exceptions-best-practices-for-synchronous-and-asynchronous-environments-39f66b59f012">Exceptions + best practices for synchronous and asynchronous code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-5-types-of-xss-attacks-tips-on-preventing-them-e6e28327748a">5 types of XSS attacks + tips on preventing them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-csrf-attacks-7-mitigation-strategies-757dfb08e7a6">CSRF attacks + 7 mitigation strategies</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-iterators-tips-on-gaining-advanced-control-over-generators-41dc3eb3bc20">Iterators + tips on gaining advanced control over generators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cryptography-how-to-deal-with-man-in-the-middle-mitm-attacks-bf8fc6be546c">Cryptography + how to deal with man-in-the-middle (MITM) attacks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-functional-style-and-how-it-compares-to-other-approaches-8a1398c73919">Functional style and how it compares to other approaches</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-3-types-of-polymorphism-f10ff4992be1">Three types of polymorphism</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-regular-expressions-regexp-e187e9082913">Regular expressions (RegExp)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-deno-a3b1153b1855">Introduction to Deno</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-creational-structural-and-behavioural-design-patterns-4-best-practices-2e8beeba744c">Creational, Structural, and Behavioural design patterns + 4 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-writing-modular-and-reusable-code-with-mvc-16c65cbd9f64">Modularity and reusability with MVC</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cross-browser-testing-tips-for-prerelease-browsers-7af653300abc">Cross-browser testing + tips for prerelease browsers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-this-variable-and-the-execution-context-12d8f04a40d3">The “this” variable and the execution context</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-high-performing-code-8-optimization-tips-cec4aab07e64">High-performing code + 8 optimization tips</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-debugging-overview-4-tips-for-async-code-5bf541c2d2ca">Debugging overview + 4 tips for async code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-call-apply-and-bind-415f6729c902">Deep dive into call, apply, and bind</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-evolution-of-graphics-500e0eb764a0">The evolution of graphics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-dockerizing-a-node-js-application-228154e9d91a">Dockerizing a Node.js application</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-decorators-a3252367fa0">A deep dive into decorators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-best-practices-for-data-compliance-133edac16450">Best practices for data compliance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-proxy-and-reflect-11748452c695">Proxy and Reflect</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-svg-and-its-use-cases-part-1-f5ab66cf426">SVG and its use cases (part 1)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-class-static-blocks-6-proposed-semantics-3487d3821b45">Class static blocks + 6 proposed semantics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-graphs-and-trees-708da0020cf8">Introduction to Graphs and Trees</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-pm2-strongloop-and-forever-4-tips-for-production-process-f456b5d45bbc">Introduction to PM2, Strongloop, and Forever + 4 tips for Production Process Managers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-advanced-svg-capabilities-part-2-a514203638cc">Аdvanced SVG capabilities (part 2)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-publisher-subscriber-pattern-9edc62ef1a68">Тhe publisher-subscriber pattern</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-stacks-and-queues-tips-for-efficient-implementation-8072a130380b">Stacks and Queues + tips for efficient implementation</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-lists-and-blockchain-implementation-practices-f5a765441175">Lists vs Blockchain + implementation practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-module-pattern-comparing-commonjs-amd-umd-and-es6-modules-437f77548437">The module pattern + comparing CommonJS, AMD, UMD, and ES6 Modules</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-different-types-of-conditional-statements-3-best-practices-756e7d3e275a">The different types of conditional statements + 3 best practices</a></li><li>T<a href="https://blog.sessionstack.com/how-javascript-works-the-different-ways-of-declaring-a-function-5-best-practices-8a0324c06fe2">he different ways of declaring a function + 5 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-factory-design-pattern-4-use-cases-7b9f0d22151d">The factory design pattern + 4 use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-guide-to-build-tools-exploring-webpack-parcel-rollup-es-build-and-2089bcf0ddb4">A guide to build tools + exploring Webpack, Parcel, Rollup, ES Build, and Snowpack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-building-a-child-process-in-node-js-776c8c51a8b0">Building a child process in Node.js</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-streams-and-their-use-cases-79d127522166">Streams and their use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-understanding-maps-and-their-use-cases-4-advantages-compared-to-objects-14e5548e00ec">Understanding Maps and their use cases + 4 advantages compared to Objects</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-webpack-cbc9c169eed7">A deep dive into Webpack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-recursion-in-javascript-what-it-is-and-how-it-is-used-eef3d734f20d">How JavaScript works: Recursion in JavaScript, What It Is, and How it is used.</a></li><li><a href="https://blog.sessionstack.com/implementation-of-grpc-in-a-nodejs-8ea8c4cdb9eb">Implementation of gRPC in a Nodejs</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-vite-965bdd8ffb42">A deep dive into Vite</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d997f93a8b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-a-deep-dive-into-esbuild-5d997f93a8b4">How JavaScript works: A deep dive into esbuild</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: A deep dive into Vite]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-a-deep-dive-into-vite-965bdd8ffb42?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/965bdd8ffb42</guid>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Wed, 04 May 2022 06:57:34 GMT</pubDate>
            <atom:updated>2023-04-11T12:57:20.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnlrQzuUNDHpnCaI-NHTaw.png" /></figure><p>This is post # 61 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-vite">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3><strong>Introduction</strong></h3><p><a href="https://vitejs.dev/">Vite</a> is a JavaScript build tool created by Evan You, the creator of Vue. And Vite simplifies the way we build and develop front-end applications. At its core, Vite primarily does two things:</p><ol><li>Serve your code locally during development</li><li>Bundle your code and assets for production.</li></ol><p>But these are primarily what other JavaScript bundlers like Webpack, Parcel, and Rollup do. So why Vite?</p><p>The problem is that before now, the JavaScript language did not have a standard module system, so web developers did not have a native way to split JavaScript codes into modules that can be exported and imported when needed. And this led to the development of different non-standard module systems for JavaScript such as<a href="https://en.wikipedia.org/wiki/CommonJS#:~:text=CommonJS%20is%20a%20project%20with,outside%20of%20the%20web%20browser."> CommonJS</a> — CJS and <a href="https://requirejs.org/docs/whyamd.html">Asynchronous module definition</a> — AMD. And tools such as Webpack that supports these module systems, and concatenates multiple javascript files and assets into a single bundle were developed.</p><p>But while Webpack is great and works well, the build process becomes increasingly slow as the app adds more code and dependencies.</p><p>However, with the addition of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules">ES module</a> — ESM to JavaScript in 2015, the JavaScript language now has a standardized module system that runs natively in the browser. And by 2020 ES modules are almost universally supported by all browsers.</p><p>Vite uses native ESM to bundle JavaScript files and application assets. And this enables Vite to load codes instantly no matter how large the size of the file might be.</p><p>Under the hood, Vite uses Rollup for the production build and features an optimized Rollup configuration out of the box. Also, Vite uses <a href="https://esbuild.github.io/">esbuild</a> for dependency pre-bundling. And this leads to significant performance improvements.</p><p>In a nutshell, Vite is a next-generation JavaScript build tool that leverages modern JavaScript APIs and toolings to simplify and speed up the build process.</p><p>Vite is fully-typed, and it ships with a lot of advanced and rich features such as Hot module replacement — HMR, <a href="https://vitejs.dev/guide/api-plugin.html#conventions">universal plugins support</a>, instant server start, out-of-the-box support for TypeScript, JSX, CSS, and more.</p><h3><strong>How Vite Works</strong></h3><p>In this section, we will look at how Vite works internally and how it is different from traditional bundle-based build tools like Webpack, Parcel, and Rollup.</p><p>There are two main issues with bundle-based build tools: slow dev-server cold-start and slow updates.</p><p>Also, we will learn about these issues and how Vite solves them.</p><p>The image below shows the setup of a bundle–based dev-server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SGRhYjRH69N6m5Z8" /><figcaption>source: <a href="https://vitejs.dev/assets/bundler.37740380.png">https://vitejs.dev/assets/bundler.37740380.png</a></figcaption></figure><p>From the image above, when we code-start the bundle-based dev-server of build tools like Webpack, Parcel, or Rollup, they have to crawl and build our entire application before it can be served on the dev-server. And this process gets increasingly slower as the application files and dependencies grow.</p><p>Vite takes a completely different approach which is made possible by leveraging ES modules.</p><p>Consider the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kYSC6WqlqDHaswc6" /><figcaption>source: <a href="https://vitejs.dev/assets/esm.3070012d.png">https://vitejs.dev/assets/esm.3070012d.png</a></figcaption></figure><p>From the image above, we can see that when we code-start a native ES-module-based dev-server like the Vite dev-server, the server starts instantly.</p><p>And this is because of the following:</p><ul><li>Vite pre-bundles the app’s dependencies — that does not change often, by using esbuild.<br>esbuild is built with Golang making 10x-100x faster than JavaScript bundlers. And this redounds to the performance of Vite.</li><li>Vite uses route-based code-splitting to determine what part of the code needs to be loaded. And it does this on the fly; thus it does not have to re-bundle the whole app.</li><li>Vite servers the code over native Es module. Thus allowing the browser to take over some part of the bundling process in development. And the result of this is that Vite now only transforms and serves source code that is requested by the browser.</li></ul><p>The other issue as noted above is slow updates. This is obvious because bundle-based build tools rebuild the entire application on each update. This approach is not optimal because it is expensive, especially for applications with large dependencies, and the update speed decreases linearly as the app size and dependencies increase. Also, reconstructing the page leads to the loss of the current state.</p><p>And to address this issue, module bundlers often use Hot module replacement — HMR.</p><p>HMR is a way of updating changed modules in a running application without updating the rest of the page.</p><p>However, in bundle-based bundlers, the update speed of HMR significantly decreases as the app size grows.</p><p>Vite performs HMR over ESM, and when a module is updated, Vite only invalidate the chain between the updated module and its closest HMR boundary.</p><p>Consequently, HMR in Vite is consistently fast regardless of the size of the application.</p><p>Also, Vite uses the browser to speed up full page reloads by leveraging HTTP headers. And strongly cache dependency module requests are supported via Cache-Control: max-age=31536000,immutable, so they don’t hit the server again.</p><p>Lastly, source code module requests are made conditional via 304 Not Modified.</p><p>And all these give Vite a significant performance advantage over bundle-based build tools.</p><p>While Vite has some clear advantages over bundle-based bundlers like Webpack and Rollup, it is interesting to see how it compares with other ESM-bundle-based bundlers like Snowpack and WSM.</p><p>We will learn about this in the next section.</p><h3><strong>Vite vs Other ESM-bundlers</strong></h3><p>Compared with other ESM bundlers like Snowpack, Vite still has some advantages. Although there are some differences in the implementation details of Vite and Snowpack both bundlers share a lot in common and enjoy some technical advantages over bundle-based build tools.</p><p>However, one of the main differences between these two bundlers is their method of building for production.</p><p>Snowpack outputs unbundled files that are transformed into separately built modules and allows the developer to feed them into any bundler of choice e.g Rollup, Webpack, or esbuild. While Vite opts for deeper integration with the Rollup bundler for the production build. And this enables Vite to support a universal API, and several other features out of the box, such as:</p><ul><li><a href="https://vitejs.dev/guide/build.html#multi-page-app">Multi-Page Support</a></li><li><a href="https://vitejs.dev/guide/build.html#library-mode">Library Mode</a></li><li><a href="https://vitejs.dev/guide/features.html#css-code-splitting">Automatic CSS code-splitting</a></li><li><a href="https://vitejs.dev/guide/features.html#async-chunk-loading-optimization">Optimized async chunk loading</a></li><li>Official <a href="https://github.com/vitejs/vite/tree/main/packages/plugin-legacy">legacy mode plugin</a> that automatically delivers the right bundle based on browser support.</li></ul><p><a href="https://github.com/preactjs/wmr">WMR</a> is another ESM-bundler that provides a similar feature set as Vite. But it is built by the Preact team for Preact. So if you are working with Preact is probably the best choice.</p><p>In the next section, we will learn how to work with Vite by setting up a Vite project and building a simple app.</p><h3><strong>Setting Up a Vite Project</strong></h3><p>Vite is used to scaffold a wide range of frontend applications as it supports Vue, React, Svelte, Preact, Vanilla JavaScript, and more. But since Vite is created by Evan You, the creator of Vue, Vite provides first-class Vue support.</p><p>To scaffold a project simply open your terminal and run:</p><p>npm create vite@latest</p><p>Choose a project name and select a template as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cqVPodj7UNTtOjkV" /></figure><p>Then follow the on-screen instruction to complete the setup.</p><p>Note: you can also select your template by using the — template flag in the CLI as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52cb2334e839b60da74f81caeae14f48/href">https://medium.com/media/52cb2334e839b60da74f81caeae14f48/href</a></iframe><p>And doing this would skip the step shown in the image above.</p><p>After selecting a template, run: npm install to install the needed dependencies.</p><p>And run: npm run dev to start the dev-server. Now you get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PEYxqrZP_DHyoGD-" /></figure><p>The app is a simple counter app. But we can improve on it. In the src directory, create a components directory and create a Counter.jsx file in it. Add the following code to the Counter.jsx file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2868c8467d1b24eb5b34bcedc0c50c94/href">https://medium.com/media/2868c8467d1b24eb5b34bcedc0c50c94/href</a></iframe><p>The Counter component above is styled using a combination of CSS module and SCSS. And this is easy because Vite provides built-in support for both. Let’s create the SCSS file. In the components directory, create a counter.module.scss file with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b183bc45d373fce8484dd966943c7f1d/href">https://medium.com/media/b183bc45d373fce8484dd966943c7f1d/href</a></iframe><p>Now, install SASS by running: npm install -D sass.</p><p>Once this is done, we need to import and use the Counter component. And to do this, update the App.js file by replacing the code with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e853ea4d525cae70438f158ce26c3f0/href">https://medium.com/media/6e853ea4d525cae70438f158ce26c3f0/href</a></iframe><p>Now you get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fR_0yUCXd7Ec5wiL" /></figure><p>Notice the app’s view updated itself because of Vite’s HMR.</p><p>Note Vite provides built-in support for CSS modules and pre-processors such as SASS, LESS, and Stylus.</p><p>Vite treats any file ending in .module.css as a CSS module. Consequently, importing such a file will import the module object.</p><p>In the small contrived app above, we have combined these features to style the counter component.</p><h3><strong>Conclusion</strong></h3><p>Vite is a French word that means fast. And Vite is blazing fast indeed.</p><p>Vite is one of the next-generation JavaScript bundlers aimed to simplify and speed up development and the build process.</p><p>In this article, we have learned a lot about Vite. And I hope you will give it a try in your next front-end project.</p><p>ESM bundlers like Vite make it much easier for software to have efficient and high-performing code. And since we all like to apply new technologies &amp; upgrade our code so even if we feel we’ve tested everything before release, it’s always necessary to verify that our users have a great experience with our product.</p><p>A solution like <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-vite">SessionStack</a> allows us to replay customer journeys as videos, showing us how our customers actually experience our product. We can quickly determine whether our product is performing according to their expectations or not. In case we see that something is wrong, we can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that we can easily understand the problem and resolve it. We can co-browse with users, segment them based on their behavior, analyze user journeys, and unlock new growth opportunities for our applications.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-vite">give SessionStack a try.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*MUSoI6XEZlYXjIP5" /><figcaption>SessionStack replaying a session</figcaption></figure><p>If you missed the previous chapters of the series, you can find them here:</p><ul><li><a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf?source=collection_home---2------1----------------">An overview of the engine, the runtime, and the call stack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e?source=collection_home---2------2----------------">Inside Google’s V8 engine + 5 tips on how to write optimized code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec?source=collection_home---2------0----------------">Memory management + how to handle 4 common memory leaks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">The event loop and the rise of Async programming + 5 ways to better coding with async/await</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-websockets-and-http-2-with-sse-how-to-pick-the-right-path-584e6b8e3bf7?source=collection_home---4------0----------------">Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79">A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">The building blocks of Web Workers + 5 cases when you should use them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service Workers, their life-cycle, and use case</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-mechanics-of-web-push-notifications-290176c5c55d">The mechanics of Web Push Notifications</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401">Tracking changes in the DOM using MutationObserver</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">The rendering engine and tips to optimize its performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-networking-layer-how-to-optimize-its-performance-and-security-f71b7414d34c">Inside the Networking Layer + How to Optimize Its Performance and Security</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-css-and-js-animations-how-to-optimize-their-performance-db0e79586216">Under the hood of CSS and JS animations + how to optimize their performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8">Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-classes-and-inheritance-transpiling-in-babel-and-113612cdc220">The internals of classes and inheritance + transpiling in Babel and TypeScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-storage-engines-how-to-choose-the-proper-storage-api-da50879ef576">Storage engines + how to choose the proper storage API</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">The internals of Shadow DOM + how to build self-contained components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-webrtc-and-the-mechanics-of-peer-to-peer-connectivity-87cc56c1d0ab">WebRTC and the mechanics of peer to peer connectivity</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-custom-elements-best-practices-on-building-reusable-e118e888de0c">Under the hood of custom elements + Best practices on building reusable components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-exceptions-best-practices-for-synchronous-and-asynchronous-environments-39f66b59f012">Exceptions + best practices for synchronous and asynchronous code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-5-types-of-xss-attacks-tips-on-preventing-them-e6e28327748a">5 types of XSS attacks + tips on preventing them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-csrf-attacks-7-mitigation-strategies-757dfb08e7a6">CSRF attacks + 7 mitigation strategies</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-iterators-tips-on-gaining-advanced-control-over-generators-41dc3eb3bc20">Iterators + tips on gaining advanced control over generators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cryptography-how-to-deal-with-man-in-the-middle-mitm-attacks-bf8fc6be546c">Cryptography + how to deal with man-in-the-middle (MITM) attacks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-functional-style-and-how-it-compares-to-other-approaches-8a1398c73919">Functional style and how it compares to other approaches</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-3-types-of-polymorphism-f10ff4992be1">Three types of polymorphism</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-regular-expressions-regexp-e187e9082913">Regular expressions (RegExp)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-deno-a3b1153b1855">Introduction to Deno</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-creational-structural-and-behavioural-design-patterns-4-best-practices-2e8beeba744c">Creational, Structural, and Behavioural design patterns + 4 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-writing-modular-and-reusable-code-with-mvc-16c65cbd9f64">Modularity and reusability with MVC</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cross-browser-testing-tips-for-prerelease-browsers-7af653300abc">Cross-browser testing + tips for prerelease browsers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-this-variable-and-the-execution-context-12d8f04a40d3">The “this” variable and the execution context</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-high-performing-code-8-optimization-tips-cec4aab07e64">High-performing code + 8 optimization tips</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-debugging-overview-4-tips-for-async-code-5bf541c2d2ca">Debugging overview + 4 tips for async code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-call-apply-and-bind-415f6729c902">Deep dive into call, apply, and bind</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-evolution-of-graphics-500e0eb764a0">The evolution of graphics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-dockerizing-a-node-js-application-228154e9d91a">Dockerizing a Node.js application</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-decorators-a3252367fa0">A deep dive into decorators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-best-practices-for-data-compliance-133edac16450">Best practices for data compliance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-proxy-and-reflect-11748452c695">Proxy and Reflect</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-svg-and-its-use-cases-part-1-f5ab66cf426">SVG and its use cases (part 1)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-class-static-blocks-6-proposed-semantics-3487d3821b45">Class static blocks + 6 proposed semantics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-graphs-and-trees-708da0020cf8">Introduction to Graphs and Trees</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-pm2-strongloop-and-forever-4-tips-for-production-process-f456b5d45bbc">Introduction to PM2, Strongloop, and Forever + 4 tips for Production Process Managers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-advanced-svg-capabilities-part-2-a514203638cc">Аdvanced SVG capabilities (part 2)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-publisher-subscriber-pattern-9edc62ef1a68">Тhe publisher-subscriber pattern</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-stacks-and-queues-tips-for-efficient-implementation-8072a130380b">Stacks and Queues + tips for efficient implementation</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-lists-and-blockchain-implementation-practices-f5a765441175">Lists vs Blockchain + implementation practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-module-pattern-comparing-commonjs-amd-umd-and-es6-modules-437f77548437">The module pattern + comparing CommonJS, AMD, UMD, and ES6 Modules</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-different-types-of-conditional-statements-3-best-practices-756e7d3e275a">The different types of conditional statements + 3 best practices</a></li><li>T<a href="https://blog.sessionstack.com/how-javascript-works-the-different-ways-of-declaring-a-function-5-best-practices-8a0324c06fe2">he different ways of declaring a function + 5 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-factory-design-pattern-4-use-cases-7b9f0d22151d">The factory design pattern + 4 use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-guide-to-build-tools-exploring-webpack-parcel-rollup-es-build-and-2089bcf0ddb4">A guide to build tools + exploring Webpack, Parcel, Rollup, ES Build, and Snowpack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-building-a-child-process-in-node-js-776c8c51a8b0">Building a child process in Node.js</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-streams-and-their-use-cases-79d127522166">Streams and their use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-understanding-maps-and-their-use-cases-4-advantages-compared-to-objects-14e5548e00ec">Understanding Maps and their use cases + 4 advantages compared to Objects</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-webpack-cbc9c169eed7">A deep dive into Webpack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-recursion-in-javascript-what-it-is-and-how-it-is-used-eef3d734f20d">How JavaScript works: Recursion in JavaScript, What It Is, and How it is used.</a></li><li><a href="https://blog.sessionstack.com/implementation-of-grpc-in-a-nodejs-8ea8c4cdb9eb">Implementation of gRPC in a Nodejs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=965bdd8ffb42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-a-deep-dive-into-vite-965bdd8ffb42">How JavaScript works: A deep dive into Vite</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: A deep dive into Webpack]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-a-deep-dive-into-webpack-cbc9c169eed7?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbc9c169eed7</guid>
            <category><![CDATA[bundler]]></category>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 14:03:36 GMT</pubDate>
            <atom:updated>2023-04-11T13:07:00.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*912xFeVbQi3B4I8Nrf0WGQ.png" /></figure><p>This is post # 58 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-webpack">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h4><strong>Introduction</strong></h4><p>Webpack is a module bundler that packages all our app assets into a production-ready bundle. Webpack does this by bundling all our app’s scripts into one file. And as a result, it minimizes HTTP requests and speeds up the site’s performance.</p><p>Also, Webpack helps us to load our app modules and their dependencies and handles different definitions and browser compatibility out of the box.</p><p>With the use of loaders, Webpack can process files such as SASS and LESS to CSS and convert JSX and modern ECMAScript into browser-friendly JavaScript. Also, Webpack uses plugins to enable us to hook into its compilation process for advanced operations.</p><p>In this article, we will take a deep dive into Webpack. And learn about its feature by elaborating on the points mentioned above using code examples.</p><p>We will start by scaffolding a simple app by running the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/070ef0a4bb5431337307958b05d8e98d/href">https://medium.com/media/070ef0a4bb5431337307958b05d8e98d/href</a></iframe><p>Next, create a public directory with an index.html file containing the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/301cba9c8a71961f9d0286fa5f8aab97/href">https://medium.com/media/301cba9c8a71961f9d0286fa5f8aab97/href</a></iframe><p>Also, create an src directory with an index.js file containing the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0c4b580e53b75bf64a6629f855368b9/href">https://medium.com/media/c0c4b580e53b75bf64a6629f855368b9/href</a></iframe><p>Now, open the package.json file and edit the scripts section as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c34d1ecafe6015250ab68b8fe5cea2e/href">https://medium.com/media/0c34d1ecafe6015250ab68b8fe5cea2e/href</a></iframe><p>Finally, we can run our app by running npm start.</p><p>In our small contrived app above, the index.js script uses the Lodash camelCase function to log our greeting to the console. However, when we check the console we get the following error:</p><p>Uncaught SyntaxError: Cannot use import statement outside a module as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D3VlmQ8wQqy31p7J" /></figure><p>This error is thrown because the browser does not know how to resolve the Lodash code, and this is where module bundlers like Webpack can help us out.</p><p>To use Webpack, we will install it as a dev dependency by running the following code:</p><p>npm i -D webpack webpack-cli</p><p>Next, we update the package.json scripts as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4b261633432470545f9c04168641032/href">https://medium.com/media/e4b261633432470545f9c04168641032/href</a></iframe><p>Now, when we run npm run build, Webpack will analyze the code in our index.js file and compile it into a dist/main.js file. And this dist/main.js is our production code. And as a result, we have to update the script src in the index.html file to dist/main.js as seen below:</p><p>&lt;script src=”../dist/main.js”&gt;&lt;/script&gt;</p><p>Now, when we run our app everything works correctly and we can see the greeting in the console as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OSuYhy0LCgfw3zAy" /></figure><p>Now, when we run our app, everything works correctly, and we can see the greeting in the console as seen below:</p><p>Modern web development involves multiple third-party modules and utility libraries like Lodash, React, Moment, etc. And following our example above, we can see why we need module bundlers like Webpack.</p><p>Also, it is important to note that we used the default settings of Webpack in our example above. But in more complex applications, we will need to customize Webpack’s default behavior. And we can do this via the webpack.config.js file.</p><p>Let’s learn about this in the next section.</p><h4><strong>Customizing Webpack</strong></h4><p>The <a href="https://webpack.js.org/configuration/">webpack.config.js</a> file is a JavaScript module that exports an object that customizes the behavior of Webpack.</p><p>The webpack.config.js file has the following properties:</p><ul><li>entry: defines the entry point to our app. In our example above, the entry point is ./src/index.js which corresponds to the default Webpack setting.</li><li>In some cases, entry can be an object. And this is particularly useful for code splitting.</li><li>output: refers to the name of the file that contains our compiled code. By default, output is main.js but we use our custom filename.</li><li>Note: when determining the file location for output, we can use the Node.js path module to resolve a consistent path name as seen below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2793017a192013bd6df2f46df64bf2a7/href">https://medium.com/media/2793017a192013bd6df2f46df64bf2a7/href</a></iframe><ul><li>mode: this can either be set to “development” which will enable useful tools for development, “production” which enables built-in optimization for production builds, or “none” which simply means no default.</li></ul><p>The mode option tells Webpack how to use its built-in optimization settings.</p><ul><li>module: the module property is used to handle the configuration of our application modules. The module property has a rules property that is an array of objects. And these objects contain the configurations for different modules such as loaders, parser options, etc.</li></ul><p>We will learn more about this option in the next section.</p><h4><strong>Loaders</strong></h4><p>By default Webpack only understands JavaScript and JSON. Loaders tell Webpack how to handle other file types. There are loaders for nearly everything in Webpack.</p><p>For example, to use CSS, we need to use both the style-loader and the css-loader together.</p><p>The css-loader loads all the CSS codes into the JS file, and the style-loader adds these styles into the DOM.</p><p>To use both loaders, install them as dependencies by running:</p><p>npm i style-loader css-loader</p><p>Then configure the webpack.config.js file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d50bddcbc4f1271186c4bd849a489bb9/href">https://medium.com/media/d50bddcbc4f1271186c4bd849a489bb9/href</a></iframe><p>Note: in our above Webpack configuration, we used modern JavaScript syntax. And for this to work correctly, you must add the type: module property to your package.json file.</p><p>Now, we can import our CSS file wherever it is required to apply the needed styles.</p><p>The benefit of this pattern is seen in cases where we have many different JS components, with each JS component injecting a different component or element into our index.html.</p><p>So with this pattern, every time we use one of these components, we can import the CSS we need for only that component instead of loading all of the CSS into the index.html file. And this enables us to modularize our CSS, and import only what we need.</p><p>Webpack loaders also enable us to perform transformations. For example, we can use babel-loader to transform our JSX code or latest JavaScript into browser-friendly vanilla JavaScript.</p><p>To perform transformation using the babel-loader, we need to install the required dependencies as seen below:</p><p>npm i -D babel-loader @babel/core @babel/preset-env</p><p>Next, we need to install the presets to use for transformation. E.g, to transform the latest JavaScript, we need to install the <a href="https://babeljs.io/docs/en/babel-preset-env">@babel/preset-env</a> preset.</p><p>Lastly, we would configure our webpack.config.js file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/074d39e38d523c1cac74039ce64a9964/href">https://medium.com/media/074d39e38d523c1cac74039ce64a9964/href</a></iframe><p>Although Webpack loaders can do a lot of the heavy lifting for us, we can tap into the Webpack compiler by using plugins.</p><p>We will learn about Webpack plugins in the next section.</p><h4><strong>Plugins</strong></h4><p>Webpack plugins enable us to hook into the Webpack compilation lifecycle.</p><p>The webpack.config.js file has a plugins property that is an array of different plugins.</p><p>To elaborate on this we would use the Webpack <a href="https://github.com/jantimon/html-webpack-plugin">HTML Webpack Plugin</a>.</p><p>When Webpack bundles our application into a dist folder we still need an index.html file that correctly points to the JS bundle in the dist folder. We can either do this manually or use the plugin mentioned above. Thus this plugin simplifies the generation of HTML files when Webpack creates our bundles. Consequently removing the need for us to supply our own template.</p><p>To use this plugin we need to install it as seen below:</p><p>`npm i — save-dev html-webpack-plugin`</p><p>Now we would configure our webpack.config.js file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e092d1305730d9af89044bcf9615a7a1/href">https://medium.com/media/e092d1305730d9af89044bcf9615a7a1/href</a></iframe><p>Note: in our above Webpack configuration, we used modern JavaScript syntax. And for this to work correctly, you must add the type: module property to your package.json file.</p><p>Now when our code is bundled, Webpack would generate the following index.html file in the dist folder that points to the path of the output file as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab3efbf3b80c5124dbac6edf6ee01abe/href">https://medium.com/media/ab3efbf3b80c5124dbac6edf6ee01abe/href</a></iframe><p>You can see this file in the dist folder after running npm run build from your CLI.</p><h4><strong>Conclusion</strong></h4><p>We have covered a lot in this article yet Webpack is packed with so many features that there are still many things to cover.</p><p>Webpack can process images and with the webpack-dev server, we can do things like hot-reloading and more. Webpack is regarded as the swiss army knife of module bundlers.</p><p>There are other module bundlers like Parcel and Rollup that still follow the concept of Webpack but try to reduce configurations. An exception, however, is Snowpack which is regarded as the feature because of its innovative <a href="https://www.snowpack.dev/concepts/how-snowpack-works#unbundled-development">unbundled development pattern</a>.</p><p>To learn more about these bundlers you can read our <a href="https://blog.sessionstack.com/how-javascript-works-a-guide-to-build-tools-exploring-webpack-parcel-rollup-es-build-and-2089bcf0ddb4">previous article on this series</a>.</p><p>We all like to apply new technologies &amp; upgrade our code. Even if we feel we’ve tested everything before release it’s always necessary to verify that our users have a great experience with our product.</p><p>A solution like <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-webpack">SessionStack</a> allows us to replay customer journeys as videos, showing us how our customers actually experience our product. We can quickly determine whether our product is performing according to their expectations or not. In case we see that something is wrong, we can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that we can easily understand the problem and resolve it. We can co-browse with users, segment them based on their behavior, analyze user journeys, and unlock new growth opportunities for our applications.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-webpack">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*fsa9LkI5fnC1JC58" /><figcaption>SessionStack replaying a session</figcaption></figure><p>If you missed the previous chapters of the series, you can find them here:</p><ul><li><a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf?source=collection_home---2------1----------------">An overview of the engine, the runtime, and the call stack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e?source=collection_home---2------2----------------">Inside Google’s V8 engine + 5 tips on how to write optimized code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec?source=collection_home---2------0----------------">Memory management + how to handle 4 common memory leaks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">The event loop and the rise of Async programming + 5 ways to better coding with async/await</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-websockets-and-http-2-with-sse-how-to-pick-the-right-path-584e6b8e3bf7?source=collection_home---4------0----------------">Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79">A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">The building blocks of Web Workers + 5 cases when you should use them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service Workers, their life-cycle, and use case</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-mechanics-of-web-push-notifications-290176c5c55d">The mechanics of Web Push Notifications</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401">Tracking changes in the DOM using MutationObserver</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">The rendering engine and tips to optimize its performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-networking-layer-how-to-optimize-its-performance-and-security-f71b7414d34c">Inside the Networking Layer + How to Optimize Its Performance and Security</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-css-and-js-animations-how-to-optimize-their-performance-db0e79586216">Under the hood of CSS and JS animations + how to optimize their performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8">Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-classes-and-inheritance-transpiling-in-babel-and-113612cdc220">The internals of classes and inheritance + transpiling in Babel and TypeScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-storage-engines-how-to-choose-the-proper-storage-api-da50879ef576">Storage engines + how to choose the proper storage API</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">The internals of Shadow DOM + how to build self-contained components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-webrtc-and-the-mechanics-of-peer-to-peer-connectivity-87cc56c1d0ab">WebRTC and the mechanics of peer to peer connectivity</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-custom-elements-best-practices-on-building-reusable-e118e888de0c">Under the hood of custom elements + Best practices on building reusable components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-exceptions-best-practices-for-synchronous-and-asynchronous-environments-39f66b59f012">Exceptions + best practices for synchronous and asynchronous code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-5-types-of-xss-attacks-tips-on-preventing-them-e6e28327748a">5 types of XSS attacks + tips on preventing them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-csrf-attacks-7-mitigation-strategies-757dfb08e7a6">CSRF attacks + 7 mitigation strategies</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-iterators-tips-on-gaining-advanced-control-over-generators-41dc3eb3bc20">Iterators + tips on gaining advanced control over generators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cryptography-how-to-deal-with-man-in-the-middle-mitm-attacks-bf8fc6be546c">Cryptography + how to deal with man-in-the-middle (MITM) attacks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-functional-style-and-how-it-compares-to-other-approaches-8a1398c73919">Functional style and how it compares to other approaches</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-3-types-of-polymorphism-f10ff4992be1">Three types of polymorphism</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-regular-expressions-regexp-e187e9082913">Regular expressions (RegExp)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-deno-a3b1153b1855">Introduction to Deno</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-creational-structural-and-behavioural-design-patterns-4-best-practices-2e8beeba744c">Creational, Structural, and Behavioural design patterns + 4 best practice</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-writing-modular-and-reusable-code-with-mvc-16c65cbd9f64">Modularity and reusability with MVC</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cross-browser-testing-tips-for-prerelease-browsers-7af653300abc">Cross-browser testing + tips for prerelease browsers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-this-variable-and-the-execution-context-12d8f04a40d3">The “this” variable and the execution context</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-high-performing-code-8-optimization-tips-cec4aab07e64">High-performing code + 8 optimization tips</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-debugging-overview-4-tips-for-async-code-5bf541c2d2ca">Debugging overview + 4 tips for async code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-call-apply-and-bind-415f6729c902">Deep dive into call, apply, and bind</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-evolution-of-graphics-500e0eb764a0">The evolution of graphics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-dockerizing-a-node-js-application-228154e9d91a">Dockerizing a Node.js application</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-decorators-a3252367fa0">A deep dive into decorators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-best-practices-for-data-compliance-133edac16450">Best practices for data compliance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-proxy-and-reflect-11748452c695">Proxy and Reflect</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-svg-and-its-use-cases-part-1-f5ab66cf426">SVG and its use cases (part 1)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-class-static-blocks-6-proposed-semantics-3487d3821b45">Class static blocks + 6 proposed semantics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-graphs-and-trees-708da0020cf8">Introduction to Graphs and Trees</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-pm2-strongloop-and-forever-4-tips-for-production-process-f456b5d45bbc">Introduction to PM2, Strongloop, and Forever + 4 tips for Production Process Managers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-advanced-svg-capabilities-part-2-a514203638cc">Аdvanced SVG capabilities (part 2)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-publisher-subscriber-pattern-9edc62ef1a68">Тhe publisher-subscriber pattern</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-stacks-and-queues-tips-for-efficient-implementation-8072a130380b">Stacks and Queues + tips for efficient implementation</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-lists-and-blockchain-implementation-practices-f5a765441175">Lists vs Blockchain + implementation practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-module-pattern-comparing-commonjs-amd-umd-and-es6-modules-437f77548437">The module pattern + comparing CommonJS, AMD, UMD, and ES6 Modules</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-different-types-of-conditional-statements-3-best-practices-756e7d3e275a">The different types of conditional statements + 3 best practices</a></li><li>T<a href="https://blog.sessionstack.com/how-javascript-works-the-different-ways-of-declaring-a-function-5-best-practices-8a0324c06fe2">he different ways of declaring a function + 5 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-factory-design-pattern-4-use-cases-7b9f0d22151d">The factory design pattern + 4 use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-guide-to-build-tools-exploring-webpack-parcel-rollup-es-build-and-2089bcf0ddb4">A guide to build tools + exploring Webpack, Parcel, Rollup, ES Build, and Snowpack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-building-a-child-process-in-node-js-776c8c51a8b0">Building a child process in Node.js</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-streams-and-their-use-cases-79d127522166">Streams and their use cases</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-understanding-maps-and-their-use-cases-4-advantages-compared-to-objects-14e5548e00ec">Understanding Maps and their use cases + 4 advantages compared to Objects</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbc9c169eed7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-a-deep-dive-into-webpack-cbc9c169eed7">How JavaScript works: A deep dive into Webpack</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: a guide to build tools + exploring Webpack, Parcel, Rollup, ES Build, and…]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-a-guide-to-build-tools-exploring-webpack-parcel-rollup-es-build-and-2089bcf0ddb4?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/2089bcf0ddb4</guid>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 13:03:23 GMT</pubDate>
            <atom:updated>2023-04-11T13:09:44.051Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How JavaScript works: a guide to build tools + exploring Webpack, Parcel, Rollup, ES Build, and Snowpack</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0FD4Dz_-QJG_k06vLSJUw.jpeg" /></figure><p>This is post # 54 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-guide-to-build-tools">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3><strong>Introduction</strong></h3><p>In its simplest form, JavaScript build tools are programs that turn development code into production code.</p><p>Over the years, build tools in JavaScript have evolved from task runners such as Grunt and Gulp to bundlers such as Browsify and Webpack, and recently we have modern module bundlers such as rollup, ES build, and Snowpack.</p><p>The primary use of build tools is to make a developer’s life easier. That is to provide an awesome developer experience.</p><p>Build tools help developers handle annoying repetitive tasks, and transpile our code to format the browser can understand. Thereby, enabling developers to leverage useful libraries and frameworks that the browser cannot understand by default. Tools like React, Vue, TypeScript, Loadash, and more are very useful in web development, but the browser does not understand the code written with these libraries. However, with a build, we can develop our app using any tool of choice and transpile our code into a final production-ready bundle that the browser can understand.</p><p>This is a list of some of the features of a JavaScript build tool:</p><ol><li>Use modern libraries or frameworks of choice</li><li>Support multiple modules definition</li><li>Minification</li><li>Concatenation</li><li>Code splitting</li><li>Tree shaking</li><li>Hot Reload</li><li>SASS or CSS frameworks</li><li>Browser compatibility — removes different configurations and loading polyfills</li></ol><p>In this article, we will focus on modern module bundlers in JavaScript.</p><p>Let’s start learning about them in the next section.</p><h3><strong>Modern JavaScript Build Tools</strong></h3><p>These modern build tools are also called bundlers or module bundlers. The primary function of a build tool is to combine multiple JavaScript files into one single file or bundle that can be used in the browser to load your application. This file or JavaScript bundle contains all our code and the third-party dependencies that are imported and used in the code.</p><p>Note, in some cases, your dependencies can have a dependency, and bundlers such as Webpack keep a dependency graph to track how everything is put together.</p><p>Bundlers are dev dependencies that help build our application code and assets for production. For example, images are optimized, dead code is removed by tree shaking, and JavaScript can be <a href="https://webpack.js.org/plugins/terser-webpack-plugin/">minified</a> or <a href="https://webpack.js.org/guides/code-splitting">split into chunks</a> and <a href="https://webpack.js.org/guides/lazy-loading">lazy-loaded</a> to improve performance.</p><p>In the next section, we will start learning about different module bundlers in JavaScript.</p><h4><a href="https://webpack.js.org/"><strong>Webpack</strong></a></h4><p>Webpack is the swiss army knife of JavaScript module bundlers and it is an advanced tool that ships out of the box with an overwhelming amount of features. And this can make Webpack difficult to learn.</p><p>As Webpack analyzes our application it builds a <a href="https://webpack.js.org/concepts/dependency-graph/">dependency graph</a> that keeps track of all our application dependencies. The dependency graph includes all the modules our application depends on and their dependencies and non-core assets, such as images or web fonts.</p><p>To work with Webpack you need to understand its core concepts:</p><ul><li>Entry</li></ul><p>This refers to our application entry point. It tells Webpack which file to begin building out its internal dependency graph.</p><p>By default, this is set to src/index.js. If the path in your application is different it won’t work.</p><ul><li>Output</li></ul><p>Once Webpack correctly points to our app’s entry file, it will analyze the code in the entry file, look up all our app dependencies, and import and compile our code into a main.js file in a dist folder. This main.js file is our production code that gets shipped to the end-user and the browser.</p><ul><li>Loaders</li></ul><p>Out of the box, Webpack only supports JavaScript and JSON files but by using <a href="https://webpack.js.org/concepts/loaders/">loaders</a>, Webpack handles preprocessing non-JavaScript files such as TypeScript, CSS, HTML, Markdown, etc.</p><ul><li>Plugins</li></ul><p>Also, Webpack allows us to hook into the compilation or bundling lifecycle by using plugins and perform tasks such as tasks like bundle optimization and asset management.</p><ul><li>Mode</li></ul><p>The mode parameter can either be none, development, or production. And depending on the configuration we enable Webpack’s optimization for that environment.</p><ul><li>Browser Compatibility</li></ul><p>Webpack supports all browsers that are <a href="https://kangax.github.io/compat-table/es5/">ES5-compliant</a> and as a result, IE8 and below are not supported.</p><p>To use Webpack we install it as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/c71bceaf66d0835e90aac4f3f31f29fb">https://gist.github.com/lawrenceagles/c71bceaf66d0835e90aac4f3f31f29fb</a></p><p>Then we update NPM scripts to run the webpack command as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/9e8fc3e30b8a6658c27293ea8442c7cd">https://gist.github.com/lawrenceagles/9e8fc3e30b8a6658c27293ea8442c7cd</a></p><p>You can configure Webpack by creating a webpack.config.js file. This file is a JavaScript module that exports an object that customizes the behavior of Webpack:</p><p><a href="https://gist.github.com/lawrenceagles/84df6c89ab01165d1a2dbc6badb8cb06">https://gist.github.com/lawrenceagles/84df6c89ab01165d1a2dbc6badb8cb06</a></p><p>In our simple Webpack configuration object above, the entry points to our entry file, and the output.filename points to the file name of our production file or final bundle. We used Node.js path module to get a more consistent path in our configuration.</p><p>There can be more complex configurations for example to handle code-splitting, etc. but the above-contrived example is simply for the purpose of the tutorial.</p><p><strong>Pros</strong></p><ul><li>Feature-packed</li><li>Great community and backing</li><li>Good CSS support</li><li>Great community plugins</li><li>Loader for anything you need</li><li>Code-splitting</li><li>Tree-shaking</li><li>Supports multiple module definitions</li></ul><p><strong>Cons</strong></p><ul><li>Not beginner-friendly</li><li>Difficult to master</li></ul><h4><a href="https://parceljs.org/"><strong>Parcel</strong></a></h4><p>Parcel is a plug-and-play module bundler that requires zero configuration. It is a beginner-friendly bundler that focuses on simplicity and works out of the box.</p><p>Parcel offers a great developer experience with a scalable architecture for building production-ready applications. And It eliminates the pain of fiddling with config files and keeping up with best practices.</p><p>The Parcel uses a multi-architecture design that enables it to build our application code in parallel by using worker thread and utilizing all our machine cores in the process. This makes the Parcel build process very fast. In addition, Parcel uses a Rust compiler for transpiling JavaScript, JSX, and TypeScript and it automatically includes content hashes in the names of all output files. And this results in long-term caching.</p><p>Also, Parcel makes debugging easy by displaying beautiful diagnostics in the terminal.</p><p>As our application grows and build requirements become complex, we can easily extend Parcel by adding our configurations in a .parcelrc file.</p><p>To use Parcel we, install it as a dev dependency as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/2b4190112db7b3e1cc71f3ac6fa819ad">https://gist.github.com/lawrenceagles/2b4190112db7b3e1cc71f3ac6fa819ad</a></p><p>Then we update our NPM scripts as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/16958e42e1c258680f854507d60d3bbb">https://gist.github.com/lawrenceagles/16958e42e1c258680f854507d60d3bbb</a></p><p>Now we can run the parcel command and start our dev server by running npm start, this would serve our application at <a href="http://localhost:1234/">http://localhost:1234/</a>.</p><p>Parcel accepts any type of file as the entry point, and it would follow up all the dependencies from there to build our app.</p><p>Also, we can run npm build to build our app for production.</p><p><strong>Pros</strong></p><ul><li>Great for beginners</li><li>Hot reloading</li><li>Content hashing</li><li>Minification</li><li>Code splitting</li><li>Tree shaking</li><li>Friendly Error logs</li><li>Awesome developer experience</li></ul><p><strong>Cons</strong></p><ul><li>Webpack is preferred for large projects.</li><li>The documentation is not robust</li></ul><h4><strong>Rollup</strong></h4><p>This is the default module bundler for <a href="https://svelte.dev/">Svelte</a>. Rollup is a blazingly fast, modern module bundler that uses the standard ECMAscript module definition— ES module.</p><p>Rollup can be used via its <a href="https://rollupjs.org/guide/en/#javascript-api">JavaScript API</a> or the <a href="https://rollupjs.org/guide/en/#quick-start">CLI</a> which is the easiest way to use Rollup.</p><p>Like Webpack, Rollup supports <a href="https://github.com/rollup/awesome">plugins</a> that can be used to change the behavior of Rollup during the build process.</p><p>Plugins add flexibility to the build process by handling tasks such as importing NPM modules, compiling codes with Babel, working with JSON, etc.</p><p>To use Rollup we install it as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/6a8e10acc8263c39b91b3591f5b90fe7">https://gist.github.com/lawrenceagles/6a8e10acc8263c39b91b3591f5b90fe7</a></p><p>Now we can try it out by running the rollup command which would print help instructions because there is no configuration or no arguments were passed. This is the same as running rollup -h or rollup — help.</p><p>We can specify the entry file and an output file as CLI arguments as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/c47ef13d65fe48b3277bf67695c2155a">https://gist.github.com/lawrenceagles/c47ef13d65fe48b3277bf67695c2155a</a></p><p>In the code above, the first argument src/main.js is the entry file, the second argument bundle.js is the output file, and the last argument cjs is the module format in this case CommonJS.</p><p>Repeating these arguments in the CLI can be annoying so to save ourselves the headache we can use the Rollup config file.</p><p>A Rollup config file is a file named rollup.config.js that is created in our root directory. It gives us more flexibility and a better developer experience than using CLI arguments.</p><p>Consider the code below:</p><p><a href="https://gist.github.com/lawrenceagles/a8a63746227d116643a2d2526821dc24">https://gist.github.com/lawrenceagles/a8a63746227d116643a2d2526821dc24</a></p><p>With our entry file, output file, and module format specified in our config file as seen above, we can now run the rollup command by using the — config or -c flag: rollup — config or rollup -c.</p><p>We can leverage the flexibility of the config file by creating more than one config file that is run independently depending on our environment.</p><p>For example, we could have a config file named rollup.config.dev.js and another named rollup.config.prod.js. And these can be run selective depending on the environment as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/bf483fb2d89e7dde2b3249786d0bf5fe">https://gist.github.com/lawrenceagles/bf483fb2d89e7dde2b3249786d0bf5fe</a></p><p>If Rollup is used locally, we run the rollup command by using NPM scripts, and for this, we will modify our package.json scripts as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/616196f3136058ffdb3517960f513dd8">https://gist.github.com/lawrenceagles/616196f3136058ffdb3517960f513dd8</a></p><p><a href="https://vitejs.dev/">Vite</a> is an opinionated superset of Rollup. In a nutshell, Vite is a wrapper around Rollup that aims to improve performance by leveraging JavaScript tools written in compile-to-native languages. And for this, Vite uses ES build under that hood.</p><p><strong>Pros</strong></p><ul><li>Simple API design</li><li>Easy to write plugins</li><li>Well documented</li><li>Tree shaking</li><li>Code splitting</li><li>Fast builds</li></ul><p><strong>Cons</strong></p><ul><li>Does not support async/await out of the box.</li></ul><h4><a href="https://esbuild.github.io/"><strong>ES Build</strong></a></h4><p>ES build is an incredibly fast JavaScript bundler built with Go.</p><p>ES build can be used via the CLI but it also provides APIs for JavaScript and GO.</p><p>ES build takes an array as its entry file and each file in this array serves as an input to the ES build bundling algorithm.</p><p>While a simple app may need only one entry file, multiple entry points are useful if there are multiple logically-independent groups of code such as a main thread and a worker thread.</p><p>Also, we can separate concerns and reduce the amount of unnecessary code the browser downloads by using multiple entry points.</p><p>To specify entry points we pass an array of file paths to ES build as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/6806c1a64a91687b961e10f8ffe3d385">https://gist.github.com/lawrenceagles/6806c1a64a91687b961e10f8ffe3d385</a></p><p>In the code above, both home.ts and dashboard.ts are entry points that would generate the corresponding output files: /out/home.js and /out/dashboard.js.</p><p>If a single entry point is specified then we use the outfile option instead of the outdir option used with multiple entry points above.</p><p>Consider the code below:</p><p><a href="https://gist.github.com/lawrenceagles/3951d05bd0d403776ab077951274a200">https://gist.github.com/lawrenceagles/3951d05bd0d403776ab077951274a200</a></p><p>Also, like Webpack, ES build support <a href="https://esbuild.github.io/api/#loader">loaders</a> and plugins. Loader change how ES build interprets files. For example, the js loader interprets files as JavaScript and the css loader interprets files as CSS. And plugins allow us to inject code into the ES build, build process.</p><p><strong>Pros</strong></p><ul><li>Blazing fast</li><li>Source map generation</li><li>Tree shaking</li><li>Minification</li><li>CLI, JavaScrit, and GO APIs</li><li>Transpilation of JSX to JS</li><li>Loader for TypeScript, JavaScript, and JSON</li><li>Support different module formats: CJS IFFI, and ESM</li></ul><p><strong>Cons</strong></p><ul><li>The plugin API is still experimental so it is unstable.</li><li>Code splitting is still a work in progress it currently only works with ESM.</li></ul><h4><strong>Snowpack</strong></h4><p>Snowpack is a modern JavaScript module bundler unique for its <a href="https://www.snowpack.dev/concepts/how-snowpack-works#unbundled-development">unbundled development</a> idea. While other bundlers use the bundled development pattern that involves running our entire application through a bundler, Snowpack implements a novel pattern that involves shipping individual files to the browser during development.</p><p>The unbundled development pattern involves serving your application unbundled during development. Each file is built once and cached, and when a file changes, Snowpack rebuilds only that file. And the result of this is that we get much faster build time since we are not rebuilding our enter application with each file change.</p><p>To use Snowpack we can install and run the Snowpack CLI command as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/c7ee9f4e9c2a6dce3e2b045dc102a77a">https://gist.github.com/lawrenceagles/c7ee9f4e9c2a6dce3e2b045dc102a77a</a></p><p>Next, we update package.json scripts as seen below:</p><p><a href="https://gist.github.com/lawrenceagles/5657ebc21a11c6074ec6e8beffd7558b">https://gist.github.com/lawrenceagles/5657ebc21a11c6074ec6e8beffd7558b</a></p><p>Now we can use Snowpack by running the code below:</p><p><a href="https://gist.github.com/lawrenceagles/8c9f51ca6d2654b3d629edfa6d4a36ac">https://gist.github.com/lawrenceagles/8c9f51ca6d2654b3d629edfa6d4a36ac</a></p><p><strong>Pros</strong></p><ul><li>Unbundled development pattern</li><li>Fast refresh and HMR</li><li>Great Cache implementation</li><li>Simple API</li><li>Plugins support</li></ul><p><strong>Cons</strong></p><h3><strong>Conclusion</strong></h3><p>JavaScript build tools make developer’s life easier. While Gulp and Grunt are great task runners, the current trend is to use a modern module bundler and NPM script as the task runner.</p><p>Webpack is great feature-packed and heavy. Parcel is great for beginners and works out of the box.</p><p>Vite is an opinionated super of Rollup and uses ES build under the hood to enhance performance.</p><p>Lastly, Snowpack, with its unbundled development is the feature.</p><p>Build tools makes it much easier for products like <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-guide-to-build-tools">SessionStack</a> to have efficient and high-performing code. SessionStack collects behavioral data during customer journeys, allowing you to replay them as a video. Since SessionStack efficiently collects and processes behavioral data, build tools are an important aspect of our stack that allows us to deliver a reliable and robust service.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-guide-to-build-tools">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*09j6R2dYioNbwv36" /><figcaption>SessionStack replaying a session</figcaption></figure><p>If you missed the previous chapters of the series, you can find them here:</p><ul><li><a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf?source=collection_home---2------1----------------">An overview of the engine, the runtime, and the call stack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e?source=collection_home---2------2----------------">Inside Google’s V8 engine + 5 tips on how to write optimized code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec?source=collection_home---2------0----------------">Memory management + how to handle 4 common memory leaks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">The event loop and the rise of Async programming + 5 ways to better coding with async/await</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-websockets-and-http-2-with-sse-how-to-pick-the-right-path-584e6b8e3bf7?source=collection_home---4------0----------------">Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79">A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">The building blocks of Web Workers + 5 cases when you should use them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service Workers, their life-cycle, and use case</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-mechanics-of-web-push-notifications-290176c5c55d">The mechanics of Web Push Notifications</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401">Tracking changes in the DOM using MutationObserver</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">The rendering engine and tips to optimize its performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-networking-layer-how-to-optimize-its-performance-and-security-f71b7414d34c">Inside the Networking Layer + How to Optimize Its Performance and Security</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-css-and-js-animations-how-to-optimize-their-performance-db0e79586216">Under the hood of CSS and JS animations + how to optimize their performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8">Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-classes-and-inheritance-transpiling-in-babel-and-113612cdc220">The internals of classes and inheritance + transpiling in Babel and TypeScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-storage-engines-how-to-choose-the-proper-storage-api-da50879ef576">Storage engines + how to choose the proper storage API</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">The internals of Shadow DOM + how to build self-contained components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-webrtc-and-the-mechanics-of-peer-to-peer-connectivity-87cc56c1d0ab">WebRTC and the mechanics of peer to peer connectivity</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-custom-elements-best-practices-on-building-reusable-e118e888de0c">Under the hood of custom elements + Best practices on building reusable components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-exceptions-best-practices-for-synchronous-and-asynchronous-environments-39f66b59f012">Exceptions + best practices for synchronous and asynchronous code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-5-types-of-xss-attacks-tips-on-preventing-them-e6e28327748a">5 types of XSS attacks + tips on preventing them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-csrf-attacks-7-mitigation-strategies-757dfb08e7a6">CSRF attacks + 7 mitigation strategies</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-iterators-tips-on-gaining-advanced-control-over-generators-41dc3eb3bc20">Iterators + tips on gaining advanced control over generators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cryptography-how-to-deal-with-man-in-the-middle-mitm-attacks-bf8fc6be546c">Cryptography + how to deal with man-in-the-middle (MITM) attacks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-functional-style-and-how-it-compares-to-other-approaches-8a1398c73919">Functional style and how it compares to other approaches</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-3-types-of-polymorphism-f10ff4992be1">Three types of polymorphism</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-regular-expressions-regexp-e187e9082913">Regular expressions (RegExp)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-deno-a3b1153b1855">Introduction to Deno</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-creational-structural-and-behavioural-design-patterns-4-best-practices-2e8beeba744c">Creational, Structural, and Behavioural design patterns + 4 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-writing-modular-and-reusable-code-with-mvc-16c65cbd9f64">Modularity and reusability with MVC</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cross-browser-testing-tips-for-prerelease-browsers-7af653300abc">Cross-browser testing + tips for prerelease browsers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-this-variable-and-the-execution-context-12d8f04a40d3">The “this” variable and the execution context</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-high-performing-code-8-optimization-tips-cec4aab07e64">High-performing code + 8 optimization tips</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-debugging-overview-4-tips-for-async-code-5bf541c2d2ca">Debugging overview + 4 tips for async code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-call-apply-and-bind-415f6729c902">Deep dive into call, apply, and bind</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-evolution-of-graphics-500e0eb764a0">The evolution of graphics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-dockerizing-a-node-js-application-228154e9d91a">Dockerizing a Node.js application</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-decorators-a3252367fa0">A deep dive into decorators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-best-practices-for-data-compliance-133edac16450">Best practices for data compliance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-proxy-and-reflect-11748452c695">Proxy and Reflect</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-svg-and-its-use-cases-part-1-f5ab66cf426">SVG and its use cases (part 1)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-class-static-blocks-6-proposed-semantics-3487d3821b45">Class static blocks + 6 proposed semantics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-graphs-and-trees-708da0020cf8">Introduction to Graphs and Trees</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-pm2-strongloop-and-forever-4-tips-for-production-process-f456b5d45bbc">Introduction to PM2, Strongloop, and Forever + 4 tips for Production Process Managers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-advanced-svg-capabilities-part-2-a514203638cc">Аdvanced SVG capabilities (part 2)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-publisher-subscriber-pattern-9edc62ef1a68">Тhe publisher-subscriber pattern</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-stacks-and-queues-tips-for-efficient-implementation-8072a130380b">Stacks and Queues + tips for efficient implementation</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-lists-and-blockchain-implementation-practices-f5a765441175">Lists vs Blockchain + implementation practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-module-pattern-comparing-commonjs-amd-umd-and-es6-modules-437f77548437">The module pattern + comparing CommonJS, AMD, UMD, and ES6 Modules</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-different-types-of-conditional-statements-3-best-practices-756e7d3e275a">The different types of conditional statements + 3 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-different-ways-of-declaring-a-function-5-best-practices-8a0324c06fe2">How JavaScript works: the different ways of declaring a function + 5 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-factory-design-pattern-4-use-cases-7b9f0d22151d">The factory design pattern + 4 use cases</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2089bcf0ddb4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-a-guide-to-build-tools-exploring-webpack-parcel-rollup-es-build-and-2089bcf0ddb4">How JavaScript works: a guide to build tools + exploring Webpack, Parcel, Rollup, ES Build, and…</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works: the factory design pattern + 4 use cases]]></title>
            <link>https://medium.com/sessionstack-blog/how-javascript-works-the-factory-design-pattern-4-use-cases-7b9f0d22151d?source=rss-9280a7128a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b9f0d22151d</guid>
            <category><![CDATA[how-javascript-works]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lawrence Eagles]]></dc:creator>
            <pubDate>Thu, 25 Nov 2021 13:06:30 GMT</pubDate>
            <atom:updated>2023-04-27T13:29:18.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7clIKcreHGyNC2iq6Y1LQ.jpeg" /></figure><p>This is post # 53 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building <a href="https://www.sessionstack.com/solutions/developers/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-the-factory-pattern">SessionStack</a>, a JavaScript tool for developers to identify, visualize, and reproduce web app bugs through pixel-perfect session replay.</p><h3><strong>Introduction</strong></h3><p>Design patterns are templates or solution schemes for solving common software development problems.</p><p>Design patterns are divided into three categories: creational patterns, structural patterns, and behavioral patterns.</p><p>Creational design patterns consist of a group of design patterns that are concerned with object creation.</p><p>Creational patterns provide object creation mechanisms that promote flexibility and reusability of our code especially in situations where we get to create many different objects.</p><p>The factory pattern is a creational design pattern that provides a generic interface for creating objects. In the factory pattern, we can specify the type of object being created and we do not need to explicitly require a constructor.</p><p>In this article, we would take a deep dive into the factory design pattern in JavaScript.</p><p>Let’s start learning about it in the next section.</p><h3><strong>The Factory pattern in dept</strong></h3><p>The factory pattern is an object-oriented — — OOP design pattern that involves creating objects by using a factory.</p><p>A factory is an object or class or a function in a functional programming paradigm for creating objects.</p><p>Although there are different object creation methods in JavaScript, the factory pattern keeps our object creation logic concise and reusable.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86c4916bc125aece879c1aa1547a0018/href">https://medium.com/media/86c4916bc125aece879c1aa1547a0018/href</a></iframe><p>In the code above, we created two Vehicle objects on the fly, by using the object literal syntax. The downside of this approach is the redundant methods: startEngine and drive.</p><p>Although in our small contrived example above these methods just log a string to the console, in reality, they could be complex. And repeating these methods the same way can lead to bugs. Also if there is a bug in the implementation of these methods we would have to fix it across all the objects they have been used.</p><p>We can clean things up by using factories. Factory gives us an object creation mechanism that is both flexible and reusable.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/575a601a38d56429db0c3fe21a167e0d/href">https://medium.com/media/575a601a38d56429db0c3fe21a167e0d/href</a></iframe><p>From our code above, we see that our factory function centralizes our object creation logic thereby, keeping our code DRY. Also, in case of any bug, we only need to fix it in the factory and it would reflect in all our code. Thus increasing our code maintainability.</p><p>Our example above is very basic and one can easily implement it using a constructor function or an ES6 class.</p><p>However, factories keep our code clean by centralizing our object creation logic and eliminating repeated constructor calls with the new operator.</p><p>The factory pattern shines if the object creation process involves dynamic factors or application configuration.</p><p>Imagine a vehicle factory that produces different kinds of vehicles: trucks, cars, buses ambulances, etc. We can implement this using the factory pattern as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f7d2e036b6e1d71cca4ed20e263d7b8/href">https://medium.com/media/8f7d2e036b6e1d71cca4ed20e263d7b8/href</a></iframe><p>In the code above, our Factory class creates a new vehicle by instantiating the Car class or the Truck vehicle class using the new operator. We determine which class to instantiate using the vehicleType parameter. In cases like these where the class to instantiate depends on dynamic factors the factory pattern is particularly useful.</p><p>Also, our factory promotes code reusability by reusing the StartEngine, driveVehicle, and stopEngine methods. So regardless of which type of vehicle is created by the factory, we can invoke these methods from the vehicle instance.</p><p>By using the factory pattern our code is also easily maintainable, so if the business expands and the factory starts producing new kinds of vehicles, we can easily refractory our implementation to handle this as seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0edabc79b80671c125db37a31743c7fc/href">https://medium.com/media/0edabc79b80671c125db37a31743c7fc/href</a></iframe><p>In the code above, we have extended our factory to support the production of buses and motorcycles. And all we have to do is to conditionally instantiate the Bus or Motorcycle class depending on the vehicleType.</p><p>Our Factory class implementation above relies heavily on class fields, a new JavaScript proposal. If you are not familiar with class fields, you can learn about them by reading our <a href="https://blog.sessionstack.com/how-javascript-works-class-static-blocks-6-proposed-semantics-3487d3821b45">previous article</a> that extensively covers class fields.</p><p>An alternative implementation is to make use of class constructors, this would allow us to create instances of our Class factory that is dedicated to creating a specific type of vehicle.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55917b1228f5815a4021161839694c95/href">https://medium.com/media/55917b1228f5815a4021161839694c95/href</a></iframe><p>In our factory above, we dynamically set the vehicleType to the class field declared in the constructor. Thus during initialization, we can specify which type of vehicle the factory instance would create. And the result of this is that TruckFactory only creates trucks and CarFactory only creates cars.</p><h3><strong>Factory pattern VS other creation patterns</strong></h3><p>We have seen above how the factory pattern can help centralize our object creation process by encapsulating all our constructor or class initialization logic.</p><p>In this section, we will compare the factory pattern with some creation patterns like constructor and singleton.</p><h4><strong>Factory pattern vs Constructors</strong></h4><p>The constructor pattern and factory pattern are similar because they are object creation patterns that return a new object. And in our previous implementation of the vehicle factory, we have seen that a factory pattern can use a constructor or class inside. But the factory pattern is preferred in cases where the object creation process depends on dynamic factors — such as when we want to dynamically create subclasses. In some cases, however, this distinction is not clear.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e13ca5a806ed5306a2b328c099b0cd8c/href">https://medium.com/media/e13ca5a806ed5306a2b328c099b0cd8c/href</a></iframe><p>In the code above, the factory and the constructor function do the same thing —they return the same car object. And in this case, the object creation is straightforward so we cannot simply prefer the factory pattern.</p><p>However, the difference between both methods is that the factory function above returns a standalone object. Which we can use without any effect on the other objects. That is a singleton. Constructors however create objects that have links to their creator.</p><p>We will elaborate on this with the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56becfea88e7d7ad82999fc17b4f5f6c/href">https://medium.com/media/56becfea88e7d7ad82999fc17b4f5f6c/href</a></iframe><p>In the code above, we see that both car1 and car2 are standalone objects with no connection with each other. Thus by setting car2.toggleEngine = undefined, car1.toggleEngine still works perfectly. But this is not so with objects created by constructors.</p><p>Consider the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aef5433252c41573a92033bfb4c723dd/href">https://medium.com/media/aef5433252c41573a92033bfb4c723dd/href</a></iframe><p>In the code above, we see that the objects car1 and car2 that are created by the constructor, are linked to the constructor. And modifying the object prototype can these objects.</p><p>This is because the constructor uses JavaScript’s prototypal inheritance under the hood to share logic between all the objects it creates.</p><p>The prototype of an object created by a constructor is the prototype of the constructor because of this rule car1 and car2 share the same prototype which contains the toggleEngine method. Thus by setting the toggleEngine to undefine— Car.prototype.toggleEngine = undefined;, the code breaks when we try to invoke it from car1.</p><p>The main takeaway is that with a factory that returns a singleton, we get complete freedom on the object to return. Also, in complex cases involving multiple constructors or classes, we can dynamically choose one constructor or class based on the set configurations.</p><p>On the contrary, a constructor basically instantiates an object with a specific prototype — the constructor’s prototype. And we can extend this prototype later in the body of the constructor function.</p><p>Thus constructors are best used for memory management systems as they only declare one set of functions that are attached to the prototype.</p><p>Also, constructors are best when the object creation process does not involve dynamic conditions.</p><h4><strong>Factory pattern vs Singleton pattern</strong></h4><p>Although the factory pattern can return a singleton, it differs from the singleton pattern because the singleton pattern ensures you always get back the same instance regardless of the type of object you are creating. In a singleton pattern, calls go through the same instance. However, the factory pattern as we have seen enables us to dynamically return different instances depending on the type of object being created.</p><h4><strong>When To Use A Factory Pattern</strong></h4><ul><li>When our object creation process involves a high level of complexity</li><li>When we need to return different instances of an object depending on some dynamic factors or application configuration</li><li>When a class can’t determine the subclass it must create</li><li>When we need to create different small objects that share some properties</li></ul><h4><strong>Pros of the factory pattern</strong></h4><ul><li>Promotes loose decoupling by separating the object creation from its implementation</li><li>Enables us to create different instances based on conditions</li><li>Promotes code reusability and maintainability</li><li>Encapsulates the constructor or class and exposes only a defined interface.</li></ul><h4><strong>Cons of the factory pattern</strong></h4><ul><li>Can be complex to implement in some cases</li><li>Depending on the complexity can be difficult to test because of the level of abstraction it introduces.</li></ul><h3><strong>Conclusion</strong></h3><p>The factory pattern is a very powerful object creation mechanism. And it is particularly useful in complex object creation processes that involve dynamic factors</p><p>They promote loose decoupling by separating the object creation from its implementation.</p><p>And they encapsulate the constructor or class and expose a defined interface to the client.</p><p>Factor patterns also foster code reusability and help keep our logic clean, concise, and maintainable.</p><p>After going through this article, I do hope you are ready to start using this pattern in your code.</p><p>Even after adopting the Factory Pattern, you should closely monitor how it impacts the performance of your code and make your products provide a <a href="https://www.sessionstack.com/blog/digital-experience-analytics-boost-growth/">better experience for your users</a>.</p><p>Even if you feel like the proper decisions have been made, it’s always necessary to verify that this is indeed true and your users have a great experience with your product.</p><p>A solution like <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-the-factory-pattern">SessionStack</a> will help you determine and further optimize the experience of your users by allowing you to replay their journeys as videos, showing you how your users actually experience your product. You can quickly determine whether your product is performing according to their expectations or not. In case you see that something is wrong, you can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that you can easily understand the problem and resolve it.</p><p>With what we have covered thus far, I sure hope you are well equipped to start building modular applications.</p><p>There is a free trial if you’d like to <a href="https://www.sessionstack.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_content=js-series-the-factory-pattern">give SessionStack a try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xKJ5O8LIdnui0DiH" /><figcaption>SessionStack replaying a session</figcaption></figure><p>If you missed the previous chapters of the series, you can find them here:</p><ul><li><a href="https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf?source=collection_home---2------1----------------">An overview of the engine, the runtime, and the call stack</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e?source=collection_home---2------2----------------">Inside Google’s V8 engine + 5 tips on how to write optimized code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec?source=collection_home---2------0----------------">Memory management + how to handle 4 common memory leaks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">The event loop and the rise of Async programming + 5 ways to better coding with async/await</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-websockets-and-http-2-with-sse-how-to-pick-the-right-path-584e6b8e3bf7?source=collection_home---4------0----------------">Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79">A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">The building blocks of Web Workers + 5 cases when you should use them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service Workers, their life-cycle, and use case</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-mechanics-of-web-push-notifications-290176c5c55d">The mechanics of Web Push Notifications</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401">Tracking changes in the DOM using MutationObserver</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda">The rendering engine and tips to optimize its performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-inside-the-networking-layer-how-to-optimize-its-performance-and-security-f71b7414d34c">Inside the Networking Layer + How to Optimize Its Performance and Security</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-css-and-js-animations-how-to-optimize-their-performance-db0e79586216">Under the hood of CSS and JS animations + how to optimize their performance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-parsing-abstract-syntax-trees-asts-5-tips-on-how-to-minimize-parse-time-abfcf7e8a0c8">Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-classes-and-inheritance-transpiling-in-babel-and-113612cdc220">The internals of classes and inheritance + transpiling in Babel and TypeScript</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-storage-engines-how-to-choose-the-proper-storage-api-da50879ef576">Storage engines + how to choose the proper storage API</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-internals-of-shadow-dom-how-to-build-self-contained-components-244331c4de6e">The internals of Shadow DOM + how to build self-contained components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-webrtc-and-the-mechanics-of-peer-to-peer-connectivity-87cc56c1d0ab">WebRTC and the mechanics of peer to peer connectivity</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-under-the-hood-of-custom-elements-best-practices-on-building-reusable-e118e888de0c">Under the hood of custom elements + Best practices on building reusable components</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-exceptions-best-practices-for-synchronous-and-asynchronous-environments-39f66b59f012">Exceptions + best practices for synchronous and asynchronous code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-5-types-of-xss-attacks-tips-on-preventing-them-e6e28327748a">5 types of XSS attacks + tips on preventing them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-csrf-attacks-7-mitigation-strategies-757dfb08e7a6">CSRF attacks + 7 mitigation strategies</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-iterators-tips-on-gaining-advanced-control-over-generators-41dc3eb3bc20">Iterators + tips on gaining advanced control over generators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cryptography-how-to-deal-with-man-in-the-middle-mitm-attacks-bf8fc6be546c">Cryptography + how to deal with man-in-the-middle (MITM) attacks</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-functional-style-and-how-it-compares-to-other-approaches-8a1398c73919">Functional style and how it compares to other approaches</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-3-types-of-polymorphism-f10ff4992be1">Three types of polymorphism</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-regular-expressions-regexp-e187e9082913">Regular expressions (RegExp)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-deno-a3b1153b1855">Introduction to Deno</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-creational-structural-and-behavioural-design-patterns-4-best-practices-2e8beeba744c">Creational, Structural, and Behavioural design patterns + 4 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-writing-modular-and-reusable-code-with-mvc-16c65cbd9f64">Modularity and reusability with MVC</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-cross-browser-testing-tips-for-prerelease-browsers-7af653300abc">Cross-browser testing + tips for prerelease browsers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-this-variable-and-the-execution-context-12d8f04a40d3">The “this” variable and the execution context</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-high-performing-code-8-optimization-tips-cec4aab07e64">High-performing code + 8 optimization tips</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-debugging-overview-4-tips-for-async-code-5bf541c2d2ca">Debugging overview + 4 tips for async code</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-deep-dive-into-call-apply-and-bind-415f6729c902">Deep dive into call, apply, and bind</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-evolution-of-graphics-500e0eb764a0">The evolution of graphics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-dockerizing-a-node-js-application-228154e9d91a">Dockerizing a Node.js application</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-a-deep-dive-into-decorators-a3252367fa0">A deep dive into decorators</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-best-practices-for-data-compliance-133edac16450">Best practices for data compliance</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-proxy-and-reflect-11748452c695">Proxy and Reflect</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-svg-and-its-use-cases-part-1-f5ab66cf426">SVG and its use cases (part 1)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-class-static-blocks-6-proposed-semantics-3487d3821b45">Class static blocks + 6 proposed semantics</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-graphs-and-trees-708da0020cf8">Introduction to Graphs and Trees</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-introduction-to-pm2-strongloop-and-forever-4-tips-for-production-process-f456b5d45bbc">Introduction to PM2, Strongloop, and Forever + 4 tips for Production Process Managers</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-advanced-svg-capabilities-part-2-a514203638cc">Аdvanced SVG capabilities (part 2)</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-publisher-subscriber-pattern-9edc62ef1a68">Тhe publisher-subscriber pattern</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-stacks-and-queues-tips-for-efficient-implementation-8072a130380b">Stacks and Queues + tips for efficient implementation</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-lists-and-blockchain-implementation-practices-f5a765441175">Lists vs Blockchain + implementation practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-module-pattern-comparing-commonjs-amd-umd-and-es6-modules-437f77548437">The module pattern + comparing CommonJS, AMD, UMD, and ES6 Modules</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-different-types-of-conditional-statements-3-best-practices-756e7d3e275a">The different types of conditional statements + 3 best practices</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-different-ways-of-declaring-a-function-5-best-practices-8a0324c06fe2">How JavaScript works: the different ways of declaring a function + 5 best practices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b9f0d22151d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sessionstack-blog/how-javascript-works-the-factory-design-pattern-4-use-cases-7b9f0d22151d">How JavaScript works: the factory design pattern + 4 use cases</a> was originally published in <a href="https://medium.com/sessionstack-blog">SessionStack Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>