<?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 Utkarsh Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Utkarsh Srivastava on Medium]]></description>
        <link>https://medium.com/@utkarshsrivastava_52177?source=rss-c151b2f5093e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*T38AEfca5qdtM6y0.</url>
            <title>Stories by Utkarsh Srivastava on Medium</title>
            <link>https://medium.com/@utkarshsrivastava_52177?source=rss-c151b2f5093e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:25:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utkarshsrivastava_52177/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[Testing Fundamentals — Mocking]]></title>
            <link>https://medium.com/smallcase-engineering/testing-fundamentals-mocking-11cc5301df01?source=rss-c151b2f5093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/11cc5301df01</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Utkarsh Srivastava]]></dc:creator>
            <pubDate>Wed, 04 May 2022 05:30:41 GMT</pubDate>
            <atom:updated>2022-05-04T05:30:41.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Fundamentals — Mocking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17IVY1uWaYRpHft5vmoxOQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@juanjodev02?utm_source=medium&amp;utm_medium=referral">Juanjo Jaramillo</a></figcaption></figure><h3>What is mocking?</h3><p>Mocking is a technique used to isolate the unit being tested by replacing dependencies with objects that you can control and inspect.</p><p>A dependency can be anything your unit depends on, but it is typically a module that the unit imports.</p><p>A unit under test may have dependencies on other units. To isolate the behaviour of the unit, you want to replace the other unit by mocks that simulate the behaviour of the real unit. This is useful if the real units are impractical to incorporate into the unit test.</p><p>In short, mocking is creating a unit that simulates the behaviour of a real unit.</p><blockquote>I promise not to use the word ‘unit’ any more in the article</blockquote><h3>Test doubles — Dummy, fake, stub, mock, spies</h3><p>In testing, there are several definitions of objects that are not real. The general term is <strong>test double</strong>.</p><p>A test double is an object that can stand in for a real object in a test, similar to how a stunt double stands in for an actor in a movie</p><p>There are five major types of test doubles : <strong>stub</strong>, <strong>mock, fake</strong>,<strong> spies, dummy</strong></p><h4>Stubs</h4><p>Stub is an object that holds predefined data and uses it to answer calls during tests. It is used when we cannot or don’t want to involve objects that would answer with real data or have undesirable side effects.</p><p>An example can be an object that needs to grab some data from the database to respond to a method call. Instead of the real object, we introduced a stub that returns the hard coded data that should be returned.</p><h4>Mocks</h4><p>Mocks are very similar to stubs, but the main difference is mocks are more ‘interaction-based’. This means that we don’t just expect the mock to return some value, but to assume that a specific order of method calls are made.</p><p>Mocks are objects that register calls they receive.</p><p>In test assertion we can verify on Mocks that all expected actions were performed.</p><p>We use mocks when we don’t want to invoke production code or when there is no easy way to verify, that intended code was executed. There is no return value and no easy way to check system state change. An example can be a functionality that calls e-mail sending service.</p><p>We don’t want to send e-mails each time we run a test. Moreover, it is not easy to verify in tests that a right email was send. Only thing we can do is to verify the outputs of the functionality that is exercised in our test. In other worls, verify that e-mail sending service was called.</p><h4>Fake</h4><p>These objects actually have a complete working implementation in them. But the implementation provided in them is some kind of a shortcut which helps us in our task of unit testing, and this shortcut renders it incapable in production. A great example of this is the in-memory database object which we can use just for our testing purposes, while we use the real database object in production.</p><h4>Spies</h4><p>Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent.</p><h4>Dummy</h4><p>When we use an object to stand in place of a real object, but never make use of the object, then the object is called a Dummy. Its usually done to fill the parameter list, so that the code compiles and the compiler stays happy.</p><blockquote>In most real world scenarios, we use <strong>mocks.</strong></blockquote><h3>Example of a testing use case</h3><figure><img alt="Function Thumbwar is accepting two players as arguments, and calling a getWinner function which returns which player won at the thumb war" src="https://cdn-images-1.medium.com/max/1024/1*xmE2UIA8qQKHl7YmPKRSog.png" /><figcaption>thumb-war.js</figcaption></figure><figure><img alt="In this test, we are checking if the output returned by thumbwar is from the arguments passed to it" src="https://cdn-images-1.medium.com/max/1024/1*-6YqcmoWFHM6p55jvnIt7Q.png" /><figcaption>thumb-war.test.js</figcaption></figure><p>Here, all we can test is whether <em>thumbWar</em> is returning one of the parameters passed to it.</p><p>This is obviously not a comprehensive test at all.</p><p>So we’ll mock the <em>getWinner</em> function.</p><p>The easiest kind of mocking is <strong>monkey patching</strong>.</p><figure><img alt="Code snippet showing monkey patching testing technique. Explained below" src="https://cdn-images-1.medium.com/max/1024/1*H2-FgckI25dfsDA2jWcOWg.png" /><figcaption>thumb-war.test.js</figcaption></figure><p>Monkey patching is a technique to add, modify, or suppress the default behaviour of a piece of code at runtime without changing its original source code.</p><p>So here, we’re mocking the implementation of the <em>getWinner </em>function after importing it, and then restoring the original implementation after the test is done.</p><p>However, This is not advisable because here we are assigning some value to a method of an imported module. This breaks an eslint rule — import/namespace.</p><p>It’s not a good idea to do this.</p><p>Note: Jest essentially does the same thing to mock too, but it performs some magic in the background, and mocks the module system, which makes the code <em>appear </em>compliant, and we don’t get any warnings/errors</p><h3>Mocking with jest</h3><p>When we talk about mocking in Jest, we’re typically talking about replacing dependencies with jest’s Mock Function.</p><p>The Mock function allows you to test the links between code by</p><ul><li>erasing the actual implementation of a function,</li><li>capturing calls to the function (and the parameters passed in those calls),</li><li>capturing instances of constructor functions when instantiated with new,</li><li>and allowing test-time configuration of return values</li></ul><p>The goal for mocking is to replace something we don’t control with something we do, so it’s important that what we replace it with has all the features we need.</p><p>The Mock Function provides features to:</p><ul><li>Capture calls</li><li>Set return values</li><li>Change the implementation</li></ul><h3>Mocking utilities in Jest</h3><h4><em>jest.fn()</em></h4><p>The simplest way to create a Mock Function instance is with <em>jest.fn().</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFaVPf7i989dsj18ZDJwTQ.png" /><figcaption>math.js</figcaption></figure><p>Here we have a bunch of util functions to add, subtract, multiply and divide the parameters passed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1FfxoY9l9oNrcMfmZvoqg.png" /><figcaption>app.js</figcaption></figure><p>We’re importing the util functions from <em>math.js</em> and using them here .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPJ3oS-72XJuDT_ahhky7A.png" /></figure><p>Now to test the <em>doAdd, </em>and <em>doSubtract</em> functions, we need to create mocks for the add and subtract functions using<em> jest.fn().</em></p><p>Now every-time the add and subtract functions are called from this test, jest would intercept the call, and would call the mocked add and subtract functions instead.</p><p>As I mentioned when we were going through monkey patching, this is very similar to what we were doing there , but here jest actually simulates the module system for us, and does some magic to make it look like our code is spec compliant, so we don’t get any eslint errors.</p><p>Here we are not testing the implementation of the function, but just whether the functions were called properly. This type of test is useful in scenarios where we want to test whether an event handler being passed to a reusable component as prop is being called correctly from the component.</p><h4>Jest Spy</h4><p>Another method of creating a function mock is a<em> jest.spyOn(</em>) method. Similar to <em>jest.fn()</em>, it creates a controlled mock.</p><p>The key difference is the fact that by default it calls the original implementation.</p><ul><li>Sometimes you only want to watch a method be called, but keep the original implementation.</li><li>Other times you may want to mock the implementation, but restore the original later in the suite.</li></ul><p>In these cases, you can use <em>jest.spyOn</em></p><p><em>jest.spyOn() </em>stores, in memory, the original implementation, so in case it has been redefined, <em>jest.spyOn()</em> allows us to restore the initial implementation using <em>mockRestore()</em> method.</p><p>A simple usage of <em>jest.SpyOn()</em>.</p><figure><img alt="example of jest.spyOn. We’re calling jest.spyOn on add function of math.js module." src="https://cdn-images-1.medium.com/max/1024/1*_MOhXIThCjyOEmVgUBCzfA.png" /></figure><p>Here we are mocking a function, but then restoring the original implementation using mockRestore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiWFjtsatjzLxZ0QfgBZxQ.png" /></figure><blockquote>Note: MockRestore is useful for tests within the same file, but unnecessary to do in an afterAll hook since each test file in Jest is sandboxed.</blockquote><p>The key thing to remember about <em>jest.spyOn</em> is that it is just sugar for the basic <em>jest.fn()</em> usage.</p><p>We can achieve the same goal by storing the original implementation, setting the mock implementation to to original, and re-assigning the original later :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQwzVGA8EqurjQ37cD0DvA.png" /></figure><p>Here, at the beginning of the test, we’re storing the <em>math.add</em> function in a variable <em>originalAdd.</em></p><p>Then we’re mocking an implementation for <em>math.add</em>, and testing for the mocked implementation.</p><p>In the end, we’re restoring <em>math.add </em>back to <em>originalAdd</em> .</p><p>This is essentially what <em>jest.spyOn()</em> does.</p><h4>Difference between using jest.fn() and jest.spyOn()</h4><p>There’s no explicit differences as such, but rather we use these two in different scenarios.</p><h4>jest.fn()</h4><ul><li>You want to mock a function and really don’t care about the original implementation of that function (it will be overridden by jest.fn())</li><li><em>Often</em> you just mock the return value</li><li>This is very helpful if you want to remove dependencies to the backend (e.g. when calling backend API) or third party libraries in your tests</li><li>It is also extremely helpful if you want to make <strong>real</strong> unit tests. You don’t care if a certain function that gets called by the unit you test is working properly, because that’s not part of its responsibility.</li></ul><h4>jest.spyOn()</h4><ul><li>The original implementation of the function is relevant for your test, but,</li><li>You want to add your own implementation just for a specific scenario and then reset it again via mockRestore() (if you just use a jest.spyOn() without mocking it further it will still call the original function by default)</li><li>You just want to see if the function was called</li></ul><h3>Mocking a module</h3><p>We can also mock a whole module using jest with <em>Jest.mock</em> .</p><p>When we mock a module, jest would simply intercept calls to all the functions of that module, and replace them with mocked functions.</p><p>Here we’re mocking the <em>Math.js</em> module</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GLoaE14HI_o0cBw-z3-Ag.png" /></figure><p>So, calling <em>jest.mock(‘./math.js’) </em>essentially sets math.js to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wd6iLMivONhuQSo6XYMESw.png" /></figure><p>This is useful in cases where we need to test multiple functions of the same module. This way, we won’t have to mock all the functions individually.</p><h3>Mocking APIs</h3><ul><li>It’s pretty straightforward to mock api responses using jest.mock()</li></ul><p>Example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cVFcw2bhbAxkw4JqhdJYA.png" /><figcaption>index.js</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iadaZlrmS0R5ZrGUpgZFgQ.png" /><figcaption>index.test.js</figcaption></figure><p>Here, when we mock the axios module, all the functions exposed by axios are replaced by jest.fn().</p><p>Then we’re returning a mock response from the axios.get method by using <em>mockResolvedValue</em></p><p>This is not an ideal setup, because here, we’ve mocked the response that we need, but there’s a bunch of other things that can go wrong and need to be tested in an api call.</p><p>There are a few issues with testing api calls like this</p><ul><li>We are not actually making an api call here. We are mocking the api handler, and stubbing a dummy response for the get method of the handler.</li><li>This leaves us open to a lot of bugs that can occur during the actual api call. Since all we’re doing here is just stubbing a dummy response , we can’t test whether the user is passing the required headers, or request params to the api. Suppose you’re making a post request, and the api has changed to accept ‘data’ instead of ‘body’. This scenario can’t be tested here.</li><li>We are mocking axios here. So now this is a dependency for our test. In the future, if we decide to shift from axios to say fetch, our tests would start breaking. This is cos we’re mocking an implementation detail here.</li></ul><p>All these issues can be solved by mocking the api handler at a more granular level, and testing for all of these scenarios, but that’ll be very tedious to do.</p><p>This is where MSW comes into the picture</p><h4>MSW</h4><p>MSW stands for mock service worker. It’s an API mocking library that uses Service Worker API to intercept actual requests.</p><p>The api is intercepted at the network level, so our application doesn’t know anything about the mock, and it actually makes the api call, it can even be seen in the networks tab. The response is just returned by our msw server.</p><p>The basic idea is this: create a mock server that intercepts all requests and handle it just like you would if it were a real server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0shMSPdlt4RB7bHCfjbSA.png" /><figcaption>index.test.js</figcaption></figure><p>Here, We’re calling the setupWorker function of msw and passing a request handler to the worker.</p><p>we’re using a get request handler, so now after the worker starts, it would intercept all the get api calls made to /albumTitles endpoint, and handle them.</p><blockquote>Note: It has handlers for all the functions of rest, and graphQl also.</blockquote><p>To respond to an intercepted request we have to specify a mocked response using a response resolver function</p><p>This accepts three arguments</p><ul><li>req — The request (req) object stores the information about a matched request. Can use this if you want to access some property from the request object. For example, req.params or req.headers etc.</li><li>res — A functional utility to create the mocked response.</li><li>ctx — a group of functions that help to set a status code, headers, body, etc. of the mocked response.</li></ul><p>Note: MockRestore is useful for tests within the same file, but unnecessary to do in an afterAll hook since each test file in Jest is sandboxed.</p><blockquote>Credit for code snippets/examples for mocking: ​​https://kentcdodds.com/blog/but-really-what-is-a-javascript-mock</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11cc5301df01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smallcase-engineering/testing-fundamentals-mocking-11cc5301df01">Testing Fundamentals — Mocking</a> was originally published in <a href="https://medium.com/smallcase-engineering">smallcase Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack — Hot Module Replacement]]></title>
            <link>https://medium.com/js-imaginea/hot-module-replacement-8b634c2a4348?source=rss-c151b2f5093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b634c2a4348</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Utkarsh Srivastava]]></dc:creator>
            <pubDate>Thu, 31 May 2018 12:27:07 GMT</pubDate>
            <atom:updated>2018-06-04T04:35:30.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZPRBrzcSmeZ7YrakJwoGQ.png" /></figure><p>One of the most useful features of webpack is its ability to watch changes in the application and then reflect those changes in the browser without reloading the application.</p><p>On the surface, it might not sound like solving a very critical problem. But trust me, it is something very useful. Let’s try and understand HMR and its purpose in web development.</p><h4>Why ?</h4><p>When we are in the middle of developing a web application, we make hundreds of changes, and most of the time we need those changes to be visible in the browser instantly. Webpack and most text editors today provide auto reload by default, where the editor keeps watching your files, and when you make any change, it reloads the application in the browser.</p><p>This way has a few issues,</p><ol><li>On every change, the whole application is rebuilt/recompiled, the browser is refreshed and the application is reloaded in the browser. All of this can take a long time when working on big applications.</li><li>Sometimes while working on something like a modal or a dialog box or the third page of a navigation wizard, when we make a change, we want to see the change taking place to the page we’re on, but the browser reloads and takes us back to the initial screen.</li><li>Live reload also loses your state, so if you are developing a feature deep within a large single page application, that can be annoying.</li></ol><p>Hot module replacement (HMR) takes care of issues like these.</p><h4>What does it do exactly ?</h4><p>What HMR basically does is, instead of reloading the whole application when it detects a change, it only replaces the modules that have been changed without reloading the application or refreshing the browser.</p><p>This can significantly speed up development as:</p><ol><li>It saves up development time by only updating what has changed.</li><li>It retains the state of the application which is normally lost during a full reload.</li></ol><p>The ‘modules’ here basically mean your JavaScript files.</p><h4>How does it work ?</h4><p>We’ve already established that HMR is a Webpack feature that updates your Javascript without a browser reload.</p><p>Webpack provides two components to make HMR possible.</p><ol><li>HMR Runtime.</li><li>HMR Server (included in webpack-dev-server as middleware).</li></ol><p>HMR Runtime is installed into the output bundle (your application) that webpack generates. The HMR Runtime is basically an extra piece of code that webpack adds to the generated output bundle .This piece of code (HMR Runtime) is responsible for receiving the module updates in your code.</p><p>The webpack compiler informs the HMR server when an update is made in any of the modules. The HMR server then notifies the HMR Runtime that an update has occurred and it provides those updates to the Runtime in .json format.</p><p>Let’s go through what happens when you make a change in your code, and how does HMR replaces only the changed module in the code without touching any other part of the application.</p><ol><li>You make a change in one of the files.</li><li>The file system picks up the change and informs webpack.</li><li>The Webpack compiler rebuilds one or more modules and notifies the<strong> HMR server</strong> that an update has been made.</li><li>The <strong>HMR server</strong> uses websockets to inform the <strong>HMR Runtime </strong>that an update has been made in the code, and that the Runtime needs to pull the update and replace the respective module.</li><li>The<strong> HMR Runtime </strong>then replaces the module(s) in the update.</li></ol><p>This is how Hot Module replacement works conceptually.</p><h4>Now how do we use it in our Application ?</h4><p>A module can only be updated if you ‘accept’ it.</p><p><strong>What does it mean for a module to be ‘accepted’ ?</strong></p><p>So to do it’s magic, webpack exposes some APIs that the user needs to use for HMR.</p><p>One such API is <strong>module.hot.accept()</strong>.</p><p>When you make a change in any module, webpack checks to see if the module is being accepted anywhere. What that means is webpack looks for the function <strong>module.hot.accept()</strong> in the parent of the component.</p><p>module.hot.accept() takes in two parameters:</p><ol><li>The path of the module which is being changed.</li><li>The callback function which handles the change.</li></ol><pre>If (module.hot) {</pre><pre>module.hot.accept(‘&lt;path of module changed&gt;’, cb( ) )</pre><pre>}</pre><p>Here<strong> module.hot</strong> property determines whether HMR is enabled or not.</p><p>Now whenever webpack detects a change in any of the modules, it looks for the <strong>module.hot.accept()</strong> function in the parent of that module. If it is not present in the parent component, webpack looks for it one level higher. The update keeps on ‘bubbling’ till it finds the module.hot.accept() function.</p><p>Once the update has been ‘accepted’, the callback function is executed. Now even though most of the time, in our callback function, we write logic to replace the respective module, technically, we can do anything in the callback function. Technically, we ‘handle’ the update in the callback (cb).</p><p>And that’s why we can say module.hot.accept() is nothing but an update handler.</p><p>Now let’s see a real world example/walk-through of setting up and using HMR.</p><p>To use HMR, we need to set up a couple of things first.</p><p>First we need to enable HMR in our application. There are a couple of ways to do that. Note that to use HMR, we need to have the webpack dev server configured.</p><p>The easiest way to enable HMR is doing it inline.</p><p><strong>1 .Enabling HRM : Inline method</strong></p><p>All you need to do here is add — hot and — inline</p><pre>//<strong>Case 1. from package.json&#39;s script</strong></pre><pre>{</pre><pre>...</pre><pre>&quot;scripts&quot;: {</pre><pre>&quot;start&quot;: &quot;webpack-dev-server --inline --hot&quot;</pre><pre>}</pre><pre>...</pre><pre>}</pre><pre>//<strong>Case 2. When WDS is installed globally</strong></pre><pre>webpack-dev-server --inline --hot</pre><pre>//<strong>Case 3. WDS is installed as a dev-dependency</strong></pre><pre>node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot</pre><p>And we’re done. That’s all you need to do to enable HMR , the inline way.</p><p>Another way to enable HMR is through the webpack config file.</p><p><strong>2</strong>. <strong>Enabling HMR through webpack.config.js</strong></p><pre>plugins: [ new webpack.HotModuleReplacementPlugin() ],</pre><pre>devServer: {</pre><pre>hot: true,</pre><pre>}</pre><p>Here all you need to do is add the HotModuleReplacementPlugin() in the webpack config file, and set the hot property to true in the devServer object.</p><p>There are more ways you can configure HMR in , but these two are the simplest and most straightforward.</p><p>At this point, our webpack project is configured for HMR. But if you fire up a browser, and make some code changes, it won’t work. Either you won’t see the update, or you’ll see a full browser refresh.</p><p>It isn’t working right now because Webpack doesn’t know yet when it is acceptable to reload a particular JS file.</p><p>To let webpack know that we’ll use the <strong>module.hot</strong> API and <strong>module.hot.accept</strong> API, provided by webpack.</p><p>Note: For the sake of this example we’re going to assume that we are working on a react application. However HMR is not related to react in any way. You can use it with any application, as long as you are using a webpack dev server.</p><p>So we will have an App component (App.js) in this example, which is going to be the top level component in our app.</p><p>Now we need to go to our entry file (index.js or main.js), this is what it typically looks like</p><pre>&lt;All the Imports&gt;</pre><pre>const render = () =&gt; {</pre><pre>ReactDOM.render(&lt;/App&gt;, document.getElementById(‘root’));</pre><pre>}</pre><pre>render();</pre><p>Now we will be adding the code we need to use HMR here:</p><pre>const render = () =&gt;  {</pre><pre>ReactDOM.render(&lt;/App&gt;, document.getElementById(‘root’));</pre><pre>}</pre><pre>render();</pre><pre>if(module.hot) {</pre><pre>module.hot.accept(‘./App.js , () =&gt; { render() }</pre><pre>}</pre><p>Here first we’re checking if hot module replacement is enabled in the project by the <strong>module.hot</strong> API.</p><p>If it is, we are using the <strong>module.hot.accept</strong> handler to handle the updates in our module.</p><p>As we mentioned above, the<strong> module.hot.accept()</strong> handler will have two parameters:</p><ol><li>The path to the module that needs to be watched. In this case we are going to watch our App module. So now whenever any updates are made in the App module, or any of the children of the App module, webpack will start looking for the module.hot.accept() method . As we discussed above, the update will keep ‘bubbling’ up till it finds module.hot.accept() in any parent module of the module being changed. In this case, it will find it in the App module.</li><li>The callback function. Now here what we’re basically doing is executing this function whenever any change is detected in App.js or any of its children. Here, we are calling the render() function in the callback. So whenever any change is detected, webpack will update the App module by calling the render function.</li></ol><p>So to recap, here we’re looking for any changes in the App module or its children, and whenever a change is detected, all we’re doing is calling the render() function in our callback, and replacing the App module with whatever the render function returns ( in this case, our updated App module).</p><p>This is how the HMR is used most commonly.</p><p>We can use it to do pretty much anything we want since we write our own logic in the update handler module.hot.accept(). HMR provides a lot of other APIs and handlers too.</p><p>If you’re interested to learn more about them, head over to <a href="https://webpack.js.org/api/hot-module-replacement/">https://webpack.js.org/api/hot-module-replacement/</a>.</p><p>This post is also published on <a href="https://blog.imaginea.com/webpack%E2%80%8A-%E2%80%8Ahot-module-replacement/">https://blog.imaginea.com/webpack%E2%80%8A-%E2%80%8Ahot-module-replacement/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b634c2a4348" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-imaginea/hot-module-replacement-8b634c2a4348">Webpack — Hot Module Replacement</a> was originally published in <a href="https://medium.com/js-imaginea">js@imaginea</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack — why and what]]></title>
            <link>https://medium.com/js-imaginea/webpack-why-and-what-4948433cc2d3?source=rss-c151b2f5093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4948433cc2d3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Utkarsh Srivastava]]></dc:creator>
            <pubDate>Tue, 10 Apr 2018 12:18:27 GMT</pubDate>
            <atom:updated>2018-04-11T10:11:58.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is webpack?</h3><p>In its broadest definition: Webpack is a bundler.</p><p>For the pedantic , it’s a module bundler. (We’ll get to the module part in a second).</p><p>So what webpack basically does is it bundles all your assets and files into , well, bundles.</p><p>But why do I need a bundler? Why can’t I just drop a script in my page?</p><p>We most certainly can, but that might lead to a problem or two in the future.</p><p>Suppose you have a script for your page. It’s about say, 500 lines of JS. No problem, I guess. We just drop the old script tag in our page.</p><p>But then we start adding more functionality to the page, and before you know it, your single script file contains 20k lines of code. Yes problem.</p><p>Managing all that code in one file is not exactly going to do any good to your stress levels. Add to that, multiple people working on the same file simultaneously.</p><p>So what do we do next? Easy. we split the code into different parts, and break our huge file into 20 smaller files, and insert the 20 &lt;script&gt; tags in our page. In a carefully chosen order of course, because you have to make sure that that utility function is available <em>before</em> you try to use it.</p><p>So now we have 20 script tags in our page, carefully inserted in a particular order. Not an ideal situation to be in, especially when you need to keep making changes in the files, and make sure the changes are made in the correct files to keep the order working.</p><p>We can write a script to concatenate all our files in one script tag, and throw that script tag into our file, but we’ll still need to ensure the correct order of the files to be concatenated, and will need to monitor the code updates in the existing files, or if any additional files need to be added, and then their order….</p><p>Long story short, our problems don’t seem to go away with this approach.</p><p>We see that just concatenating all the files in the correct order is not doing us much good.</p><p>A better approach would be if somehow each file could tell us what other files it requires ( it’s dependencies) and then we can include that mapping in our earlier concatenation approach.</p><p>This is where webpack steps in.</p><p>There are mechanisms for specifying dependencies and imports in ES6 and nodeJS.</p><p>Webpack uses these mechanisms to build a dependency graph of all the files and their dependencies, and bundle all the files.</p><p>The details of how webpack does the bundling requires steps like adding a little boilerplate code before and after each file, and converting it in a set of functions, and then executing these functions in a controlled manner, but We’ll save those details for a later post.</p><p>However, I’ll try to give a fifty thousand feet view of how the webpack bundling works.</p><p>You specify an entry file in the webpack configuration , and the process starts from there.</p><p>Webpack goes through the dependencies of each file recursively, and resolves every dependency until the traversal has completed.</p><p>The resolver first verifies if the respective files for all the dependencies are present. If they are, it transforms every file in a module, and creates a dependency graph of all the modules.</p><p>Then it bundles all of this in one file ( specified as the ‘output’ file in the configuration).</p><p>It maintains a registry of all the modules, so they can be correctly called/executed whenever they are required.</p><h3><strong>Loaders</strong></h3><p>The motivations behind webpack is to gather all your dependencies, which includes not just code, but other assets as well, and generate a dependency graph.</p><p>Bundlers are only prepared to handle JS files, so webpack needs to preprocess all the other files and assets before they get bundled. This is where Loaders come into the picture.</p><p>Webpack supports a large variety of formats through loaders.</p><p>According to the official documentation, Loaders are transformations that are applied on the source code of a module.</p><p>Basically loaders allow you to do a number of things like transform files from a different language to javascript, or inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules.</p><p>This is how we use loaders:</p><pre>{</pre><pre>test: /\.css$/,</pre><pre>use: [“style-loader”, “css-loader”],</pre><pre>}</pre><p>Here,we are testing if the file is a css file, and if it is, we are using the css-loader and the style-loader to transform the file before bundling it ( webpack applies the loaders in order from right to left)</p><p>The way a loader gets matched against a resolved file can be configured in multiple ways, including by file type and by location within the file system.</p><p>Webpack’s flexibility even allows you to apply a specific transformation to a file based on where it was imported into the project.</p><p>Apart from creating a dependency graph, and bundling the modules, webpack can perform a number of tasks.</p><p>Webpack gives you control over how to treat different assets it encounters. For example, you can decide to inline assets to your JavaScript bundles to avoid requests. Webpack also allows you to use techniques like CSS Modules to couple styling with components, and to avoid issues of standard CSS styling. This flexibility is what makes webpack so valuable.</p><p>Apart from all the functionalities provided out of the box by loaders, we can perform a lot of advanced tasks through Plugins.</p><p>Plugins can intercept runtime events supplied by webpack. Webpack provides hooks for all the runtime events. And we can tap into these hooks to do a lot of things</p><p>A good example would be bundle extraction performed by the ExtractTextPlugin which, when used with a loader, extracts CSS files out of the bundle and into a separate file. Without this step, CSS would be inlined inPlugins can intercept runtime events supplied by webpack. A good example is bundle extraction performed by the ExtractTextPlugin which, when used with a loader, extracts CSS files out of the bundle and into a separate file. Without this step, CSS would be inlined in the resulting JavaScript, as webpack treats all code as JavaScript by default.</p><p>At its core, webpack relies on configuration. Here is a sample configuration that covers to main point</p><pre>const webpack = require(&quot;webpack&quot;);</pre><pre>module.exports = {<br>  // Where to start bundling<br>  entry: {<br>    app: &quot;./entry.js&quot;,<br>  },</pre><pre>// Where to output<br>  output: {<br>    // Output to the same directory<br>    path: __dirname,</pre><pre>// Capture name from the entry using a pattern<br>    filename: &quot;[name].js&quot;,<br>  },</pre><pre>// How to resolve encountered imports<br>  module: {<br>    rules: [<br>      {<br>        test: /\.css$/,<br>        use: [&quot;style-loader&quot;, &quot;css-loader&quot;],<br>      },<br>      {<br>        test: /\.js$/,<br>        use: &quot;babel-loader&quot;,<br>        exclude: /node_modules/,<br>      },<br>    ],<br>  },</pre><pre>// What extra processing to perform<br>  plugins: [<br>    new webpack.DefinePlugin({ ... }),<br>  ],</pre><pre>// Adjust module resolution algorithm<br>  resolve: {<br>    alias: { ... },<br>  },<br>};</pre><p>To wrap up, Webpack is a great tool which can be easily used out of the box to automatically load and bundle CSS and other files and assets in addition to JS , with the help of an easy to set up config file. And at the same time, offers the users the freedom to perform much more complex tasks with its vast configurable options, and plugins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4948433cc2d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-imaginea/webpack-why-and-what-4948433cc2d3">Webpack — why and what</a> was originally published in <a href="https://medium.com/js-imaginea">js@imaginea</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>