<?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 Mark Brouch on Medium]]></title>
        <description><![CDATA[Stories by Mark Brouch on Medium]]></description>
        <link>https://medium.com/@markbrouch?source=rss-6829485f4781------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GtXXkJKfavQRTHB1gvHmeQ.jpeg</url>
            <title>Stories by Mark Brouch on Medium</title>
            <link>https://medium.com/@markbrouch?source=rss-6829485f4781------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:57:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@markbrouch/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[A Practical Example of Nullish Coalescing]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://codeburst.io/a-practical-example-of-nullish-coalescing-38ede5855928?source=rss-6829485f4781------2"><img src="https://cdn-images-1.medium.com/max/2600/1*-MjaxJaOiCbUTxpXLgihoQ.jpeg" width="6000"></a></p><p class="medium-feed-snippet">Nullish coalescing is a brand new logical operator (??) for the JavaScript programming language. Let&#x2019;s take a look at one practical&#x2026;</p><p class="medium-feed-link"><a href="https://codeburst.io/a-practical-example-of-nullish-coalescing-38ede5855928?source=rss-6829485f4781------2">Continue reading on codeburst »</a></p></div>]]></description>
            <link>https://codeburst.io/a-practical-example-of-nullish-coalescing-38ede5855928?source=rss-6829485f4781------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ede5855928</guid>
            <category><![CDATA[es2020]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nullish-coalescing]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mark Brouch]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 19:18:32 GMT</pubDate>
            <atom:updated>2020-06-07T22:37:02.783Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Automate Your Home Theater Lights From The Cloud]]></title>
            <link>https://medium.com/hackernoon/automate-your-home-theater-lights-from-the-cloud-cdb29a8685a6?source=rss-6829485f4781------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdb29a8685a6</guid>
            <category><![CDATA[philips-hue]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[side-project]]></category>
            <category><![CDATA[plex]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mark Brouch]]></dc:creator>
            <pubDate>Tue, 02 May 2017 16:36:41 GMT</pubDate>
            <atom:updated>2017-07-19T12:15:21.941Z</atom:updated>
            <content:encoded><![CDATA[<h4>Connecting Plex Media Server to Hue Lighting System using AWS API Gateway and Lambda</h4><p>This weekend I set out to do something cool with my <a href="http://www2.meethue.com/en-us/">Phillips Hue Lights</a> that I had installed in my basement’s home theater. The goal: <strong>Automatically dim the lights to ‘theater mode’ when I play a movie.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*gR6T5qGYcabbctEySXgNeA.gif" /></figure><h3>The Setup</h3><p>I live in a split-level apartment in Chicago with a finished basement area that I use as a home theater. Last October I installed <a href="https://www.amazon.com/Philips-432690-Equivalent-Single-Light/dp/B00HNLQQ7K">6 Color Hue Can Lights</a>, a <a href="https://www.amazon.com/Philips-Bloom-Works-Amazon-Alexa/dp/B00I12YFP0">Hue Bloom</a>, and a <a href="https://www.amazon.com/Philips-Lightstrip-Generation-Works-Amazon/dp/B014H2OXYU/ref=pd_sim_60_3?_encoding=UTF8&amp;pd_rd_i=B014H2OXYU&amp;pd_rd_r=QJMSJY8Q5NMEMEK5P964&amp;pd_rd_w=ZXNkp&amp;pd_rd_wg=Y4e6J&amp;psc=1&amp;refRID=QJMSJY8Q5NMEMEK5P964">Hue LED Strip</a> in the basement which I can control with my iPhone or Amazon Echo Dot. I set up several Hue lighting “scenes” so that I can easily change the brightness and color of the lights in the basement, including a “Theater Mode” which turns off all of the lights except the LED strip as a backlight behind the TV stand.</p><p>For movie streaming, I have a computer in my office running <a href="https://www.plex.tv/">Plex Media Server</a> which I use to stream to a variety of devices on or off my local network. I also have an Apple TV hooked up to my TV in the basement with the <a href="https://www.plex.tv/apps/streaming-devices/apple-tv/">Plex app</a> installed.</p><p>This setup has worked pretty well for awhile now, and I especially love that I can tell Alexa to turn the lights on/off without even getting off the couch, but I felt we could go even lazier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*2tKZzeWgi_vCUrcFdiU4zA.gif" /></figure><blockquote>“If necessity is the mother of invention, then laziness is the father.”</blockquote><h3>The Plan</h3><p>I wanted a way for the lights to automatically go into Theater Mode (lights off) when I play a movie, and then come back to Dimmed Mode (lights on) when the movie ends or when I pause to use the bathroom or make some more popcorn. (In the future, popcorn will be delivered automatically from the cloud.)</p><p>Plex recently <a href="https://support.plex.tv/hc/en-us/articles/115002267687-Webhooks">added webhooks</a> for several events, including play/pause. Hue lights have always been sold with hobbyist programmers in mind and include a <a href="https://developers.meethue.com/">robust API</a> (although it could be much better — more on that later). With these two endpoints in place, all I had to do was get them to talk to each other.</p><p>Given that I already had a server on my network to host Plex, it would make sense to quickly spin up an Express server on Node.js to forward webhook events to my Hue lighting hub, but baremetal servers are sooo 2015. No, this project sounded like a good opportunity to go serverless in the AWS cloud!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7y4y6m3W4FAVsqbQseFsqQ.png" /><figcaption>Data flow diagram: Plex Webhook → AWS API Gateway → AWS Lambda → Hue Lights</figcaption></figure><p>Disclaimer: I’m an AWS novice. Send me a message if any of my configuration could be improved!</p><h3>Setting up the Lambda function</h3><p>In order to get the Plex server talking to the Hue lights, we’ll need to implement a small amount of webhook parsing logic — a perfect job for <a href="https://aws.amazon.com/lambda/">AWS Lambda</a>. For the uninitiated — a Lambda function is basically a function in the cloud. They’re great for building out microservices, or in this case, connecting APIs.</p><p>We’re essentially going to build an “If This Then That”-style function with the following logic:</p><ul><li>📺 Check Plex webhook payload if the action was triggered by my AppleTV.</li><li>📽 Check Plex webhook payload if the triggered action came from a movie.</li><li>🌑 Set Hue lights to Theater Mode if Plex event is Play or Resume.</li><li>🌕 Set Hue lights to Dimmed Mode if Plex event is Pause or Stop.</li></ul><p>To get started, we’ll need to create a new Lambda. We can do this from the AWS dashboard, but I prefer to use the NPM package <a href="https://github.com/motdotla/node-lambda">node-lambda</a> for configuration, deployment, and testing. <a href="https://github.com/markbrouch/plex-webhook">You can see the full source for my Lambda function on GitHub.</a></p><p>I won’t go into the details of setting up a new Lambda function, other than that we’ll need to provide the lambda-access role so that we can connect to our API Gateway later on. Lambda also (finally) supports Node v6.10, and we’ll be using that as our execution environment. Once our Lambda is configured, we’ll be able to setup API Gateway.</p><h3>Configuring API Gateway</h3><p><a href="https://aws.amazon.com/api-gateway/">AWS API Gateway</a> is the interface we’ll use to connect our Plex webhook to our Lambda function. API Gateway is capable of a highly sophisticated API architecture, but for our purposes we’ll need only a single POST endpoint that will forward on to the Lambda function.</p><p>After we create a new API, we’ll create a single POST resource at / that will handle our webhook request. Next, we’ll configure the POST resource’s Integration Request as such:</p><ul><li>Integration type: Lambda function</li><li>Lambda Region: The region of our Lambda function</li><li>Lambda Function: The name of our Lambda function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwZboBrfqyBw-oF6U0sYnw.png" /></figure><p>The Plex webhook doesn’t deliver its payload in the application/json content-type that our Lambda function needs, so we’ll need to massage the request into a Lambda-friendly format. Since there’s no way to parse the multipart form data coming from the Plex webhook in API Gateway, we’re just going to pass it through as Base64 encoded binary instead and then deconstruct it later in our Lambda function.</p><p>We’ll need to <a href="https://aws.amazon.com/about-aws/whats-new/2016/11/binary-data-now-supported-by-api-gateway/">enable binary support</a> on our API and add the binary media type multipart/form-data so that API Gateway doesn’t try to parse JSON from our webhook. Then, back in our POST resource’s Integration Request tab, we’ll need to add the following Body Mapping Template for multipart/form-data content-type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bRffLupedapAe4741XdPw.png" /></figure><pre>{<br>  &quot;body&quot;: &quot;$input.body&quot;,<br>  &quot;headers&quot;: {<br>    #foreach($param in $input.params().header.keySet())<br>      &quot;$param&quot;:<br>        &quot;$util.escapeJavaScript($input.params().header.get($param))&quot;<br>      #if($foreach.hasNext),#end<br>    #end<br>  }<br>}</pre><blockquote>API Gateway uses Apache’s <a href="http://velocity.apache.org/engine/devel/vtl-reference.html">Velocity Templating Language (VTL)</a> for body mapping templates</blockquote><p>This will wrap our raw encoded request in body and also forward all headers coming from the Plex webhook in headers. That’s all the configuration needed for API Gateway, we can now click Actions → Deploy API. Create a new Deployment stage and hit Deploy. If successful, you will be taken to the Stage Editor for the stage you just created and deployed to. Copy the Invoke URL to <a href="https://support.plex.tv/hc/en-us/articles/115002267687-Webhooks">a new Plex webhook under Account Settings</a>.</p><h3>Unpacking the payload in Lambda</h3><p>Our Lambda function exposes a handler which our API Gateway will invoke with the forwarded Plex webhook as the event argument. We’ll need to unpack the event body, which will be a multipart form, and then parse it to get the payload JSON. To do this, we’ll use an NPM package called <a href="https://github.com/mscdex/busboy">Busboy</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*nwtScI_Fd9vhOOb6hRBbkg.gif" /><figcaption>Busboy loves parsing your multipart form data as much as this one loves bussing tables.</figcaption></figure><p>Busboy is a low-level writeable stream used by several Express middlewares like Multer for parsing multipart form data. Usage is simple — we’ll just pass the headers to the Busboy initializer and then pipe in the Base64 encoded body. Busboy will then fire events for each form field it encounters. Here’s what our handler code looks like:</p><pre><em>const</em> Busboy = require(&#39;busboy&#39;);</pre><pre><em>exports</em>.handler = (<em>event</em>, <em>context</em>, <em>callback</em>) <em>=&gt;</em> {<br>  // Busboy expects headers to be lower-case<br>  <em>const</em> headers = {};<br>  <em>Object</em>.keys(event.headers).forEach(<br>    <em>key</em> <em>=&gt;</em> (headers[key.toLowerCase()] = event.headers[key])<br>  );</pre><pre><em>  const</em> busboy = new Busboy({<br>    headers<br>  });</pre><pre>  // For each field in the request<br>  busboy.on(&#39;field&#39;, (<em>fieldname</em>, <em>value</em>) <em>=&gt;</em> {<br>    // Check for the Plex webhook&#39;s payload field<br>    if (fieldname === &#39;payload&#39;) {<br>      <em>const</em> payload = JSON.parse(value);</pre><pre>      // Read the payload to control Hue lights<br>      readPayload(payload);<br>      <br>      // Send payload in response for testing &amp; debugging<br>      callback(null, {<br>        payload<br>      });<br>    }<br>  });</pre><pre>  // Pipe Base64 encoded body from API Gateway to Busboy<br>  busboy.write(<em>Buffer</em>.from(event.body, &#39;base64&#39;));<br>};</pre><p>The readPayload() function will contain our logic for connecting to Hue, but you could use this handler code as a boilerplate for connecting a Plex webhook to any external service.</p><p>We can now test our event handler by creating a mockevent.json if you’re using node-lambda, or you can console.log() to the AWS CloudWatch logs.</p><h3>Controlling Hue lights with Lambda</h3><p>With our Plex webhook payload in proper JSON format, we’re ready to talk to our Hue lights, but first we’ll need to prepare our Lambda for the Hue API. We’ll add some environment variables for the various Hue IDs we’ll need, and perform a rather hacky authentication to connect to our Hue Bridge from our Lambda function that exists outside our local network.</p><p>Phillips provides a fairly robust RESTful API for controlling most aspects of a Hue lighting system from within the same local network, but does not provide any documentation for controlling the lights from the Internet, though it is possible. <a href="http://blog.paulshi.me/technical/2013/11/27/Philips-Hue-Remote-API-Explained.html">Paul Shi wrote an excellent blog post</a> on how to “hack” into a Hue Bridge from outside its local network. Use Paul’s guide to get the BRIDGEID and ACCESSTOKEN.</p><p>We’re going to store the BRIDGEID and ACCESSTOKEN as environment variables in our Lambda, along with several other variables:</p><ul><li>HUE_TOKEN: ACCESSTOKEN</li><li>HUE_BRIDGE_ID: BRIDGEID</li><li>HUE_SCENE_THEATER: The scene ID for our Theater scene</li><li>HUE_SCENE_DIMMED: The scene ID for our Dimmed scene</li><li>HUE_GROUP_ID: The group ID for the group containing our lights</li><li>PLAYER_UUID: The UUID of the AppleTV device from the Plex webhook</li></ul><p>You can find the scene IDs and group ID by making a GET <a href="https://www.meethue.com/api/getbridge">https://www.meethue.com/api/getbridge</a> request as explained in Paul’s blog post.</p><p>Our readPayload() function will perform the checks on the payload to see what, if any, action should be sent to the Hue API, and will then construct and send the appropriate request:</p><pre><em>const</em> https = require(&#39;https&#39;);</pre><pre><em>const</em> readPayload = <em>payload</em> <em>=&gt;</em> {<br>  // Plex webhook event constants<br>  <em>const</em> PLAY = &#39;media.play&#39;;<br>  <em>const</em> PAUSE = &#39;media.pause&#39;;<br>  <em>const</em> RESUME = &#39;media.resume&#39;;<br>  <em>const</em> STOP = &#39;media.stop&#39;;</pre><pre><em>  const</em> { event, Player, Metadata } = payload;</pre><pre>  // https options<br>  <em>const</em> options = {<br>    hostname: &#39;www.meethue.com&#39;,<br>    path: `/api/sendmessage?token=${process.env.HUE_TOKEN}`,<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;<br>    }<br>  };</pre><pre>  if (<br>    process.env.PLAYER_UUID === Player.uuid &amp;&amp;  // Event came from the correct player<br>    Metadata.type === &#39;movie&#39; &amp;&amp;  // Event type is from a movie<br>    (event === PLAY || event === STOP || event === PAUSE || event === RESUME) // Event is a valid type<br>  ) {<br>    <em>const</em> scene = event === PLAY || event === RESUME<br>      ? process.env.HUE_SCENE_THEATER // Turn the lights off because it&#39;s playing<br>      : process.env.HUE_SCENE_DIMMED; // Turn the lights on because it&#39;s not playing</pre><pre>    // Construct Hue API body<br>    <em>const</em> body = `clipmessage={ bridgeId: &quot;${process.env.HUE_BRIDGE_ID}&quot;, clipCommand: { url: &quot;/api/0/groups/${process.env.HUE_GROUP_ID}/action&quot;, method: &quot;PUT&quot;, body: { scene: &quot;${scene}&quot; } } }`;</pre><pre>    // Send request to Hue API<br>    <em>const</em> req = https.request(options);<br>    req.write(body);</pre><pre>    req.end();<br>  }<br>};</pre><p>And that’s it! The lights should now go into Theater Mode when a movie starts playing on the AppleTV and will come back on in Dimmed Mode when the movie is paused or stops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*6rvCih3a3ICvErq2J__uGA.gif" /></figure><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdb29a8685a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/automate-your-home-theater-lights-from-the-cloud-cdb29a8685a6">Automate Your Home Theater Lights From The Cloud</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Shouldn’t Use ‘var’ Anymore]]></title>
            <link>https://medium.com/hackernoon/why-you-shouldnt-use-var-anymore-f109a58b9b70?source=rss-6829485f4781------2</link>
            <guid isPermaLink="false">https://medium.com/p/f109a58b9b70</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[es2015]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Mark Brouch]]></dc:creator>
            <pubDate>Mon, 17 Oct 2016 22:14:07 GMT</pubDate>
            <atom:updated>2017-07-14T11:54:45.159Z</atom:updated>
            <content:encoded><![CDATA[<h4>And how ‘let’ solves a common JavaScript “gotcha”…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*_w57I_pvH1qr6BNi_pR9mw.png" /></figure><p>I’ve been writing JavaScript using the ES2015 (ES6) syntax for awhile now and have grown to appreciate many of the language changes for their elegance and simplicity. One of the first and easiest changes I adapted to was using let/const instead of var. However, I took for granted the benefit let provides over var; it isn’t just a flashy new syntax for var, but rather provides an important scoping mechanism.</p><blockquote>I took for granted the benefit let provides over var...</blockquote><p>It’s worth noting first that <em>the vast majority of variables I declare are best suited for using </em><em>const</em> instead of let/var. This is because const will throw an error if an attempt is made to change its value after it has been declared, a useful feature to prevent accidental mutation. However, a mutable variable is often needed, particularly as a counter in looping scenarios. But why should you use let instead of var for these situations, if they both provide the basic mutability required of them?</p><p>The simple answer is that <strong>let provides block-scoping</strong> that is absent in the function-scoped var. This explanation obviously begs a practical example. Allow me to demonstrate this important distinction using a classic front-end engineering interview question:</p><p>In this example, what will be printed in the console?</p><pre>var callbacks = [];<br>(function() {<br>  for (var i = 0; i &lt; 5; i++) {<br>    callbacks.push( function() { return i; } );<br>  }<br>})();</pre><pre>console.log(callbacks.map( function(cb) { return cb(); } ));</pre><p>In this example, we loop 5 times, each time pushing a function into the callback array. After the array is filled with 5 functions, we run each of them, logging their result to the console. A novice engineer might answer (incorrectly) that the result is [0, 1, 2, 3, 4], <em>a reasonable analysis, but one that falls victim to the JavaScript “hoisting” gotcha</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*8Fu7Zf7FToKMRUIMSqkSXw.gif" /><figcaption>Don’t be a victim. Avoid the hoisting trap with ‘let’!</figcaption></figure><p>The correct answer is actually [5, 5, 5, 5, 5], and makes sense when you consider what hoisting does behind the scenes:</p><pre>var callbacks = [];<br>(function() {<br>  <strong>var i;</strong><br>  for (<strong>i</strong> = 0; i &lt; 5; i++) {<br>    callbacks.push( function() { return i; } );<br>  }<br>})();</pre><pre>console.log(callbacks.map( function(cb) { return cb(); } ));</pre><p>Notice how JavaScript hoists the variable declaration to the top of the function block, causing the value of i to be 5 by the time each of the callback functions have executed, since the for loop has incremented completely before any of these functions are called.</p><p>There are a number of ways to classically solve this problem and get the script to log [0, 1, 2, 3, 4] to the console, but let gives us a very simple solution:</p><pre>var callbacks = [];<br>(function() {<br>  for (<strong>let</strong> i = 0; i &lt; 5; i++) {<br>    callbacks.push( function() { return i; } );<br>  }<br>})();</pre><pre>console.log(callbacks.map( function(cb) { return cb(); } ));</pre><p>That’s it — <strong>just replace </strong><strong>var with </strong><strong>let</strong> and the example works as expected! This is thanks to the block-scoping behavior of let. Rather than being hoisted to the top of the function’s scope, <em>let stays in the block scope of the loop</em>, causing a separate instance of i for each iteration.</p><p>So, should you ever use var? As you have likely gathered from the title of this article, I am of the opinion that <strong>you should never use </strong><strong>var</strong>. Technically, var is still useful in situations where you want to maintain function scope instead of block scope, but I am of the firm belief that if you need to rely on an unintuitive hoist to get your script to work, you have bigger problems 😜.</p><p><strong>Update:</strong> In response to two of the most common points of discussion readers are bringing up:</p><ol><li>It is true that const isn’t <em>truly</em> immutable. For instance:</li></ol><pre>const myNotQuiteImmutableObject = {<br>  thisCanBeChanged: &quot;not immutable&quot;<br>};</pre><pre>myNotQuiteImmutableObject.thisCanBeChanged = &quot;see I changed it.&quot;;</pre><p>However, this still prevents basic mutation like:</p><pre>const immutableString = &quot;you can&#39;t change me&quot;;</pre><pre>immutableString = &quot;D&#39;OH!&quot;; // error</pre><p>If you need real immutability, check out Facebook’s excellent <a href="https://facebook.github.io/immutable-js/">Immutable</a> library.</p><p>2. “let isn’t supported in {mySuperAncientBrowser}.” This is true, and even <a href="http://caniuse.com/#feat=let">somewhat recent browsers still don’t have support for </a><a href="http://caniuse.com/#feat=let">let</a>. This has an obvious and easy solution: Use <a href="https://babeljs.io/">Babel</a>. Babel will allow you to use all the best and latest features of JavaScript and then transpile into a vocabulary that even simple old IE8 can understand (with some exceptions).</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><a href="https://goo.gl/Ahtev1"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f109a58b9b70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/why-you-shouldnt-use-var-anymore-f109a58b9b70">Why You Shouldn’t Use ‘var’ Anymore</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use ES7 Object Rest Operator to Omit Properties]]></title>
            <link>https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90?source=rss-6829485f4781------2</link>
            <guid isPermaLink="false">https://medium.com/p/38a3ecffe90</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es7]]></category>
            <dc:creator><![CDATA[Mark Brouch]]></dc:creator>
            <pubDate>Thu, 13 Oct 2016 22:00:06 GMT</pubDate>
            <atom:updated>2018-06-04T16:56:52.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtR7xSOCAJkqsOv9IL2KNA.png" /></figure><p>I was perusing the <a href="https://github.com/airbnb/javascript/blob/master/README.md#objects--rest-spread">Airbnb JavaScript Style Guide</a> today when I came across an intriguing pattern that cleverly uses the ES7 Object Rest Spread operator to omit properties from an object.</p><p>Ready? Here it is:</p><pre>const myObject = {<br>  a: 1,<br>  b: 2,<br>  c: 3<br>};<br>const { a, ...noA } = myObject;</pre><pre>console.log(noA); // =&gt; { b: 2, c: 3 }</pre><p>This confused me at first, so I’ll explain. We are using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Object Destructuring</a> in conjunction with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">Object Rest Spread operator</a> to separate our large myObject into separate parts a and noA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*wV15allsqjmKsyLEFs1gVg.gif" /></figure><p>It’s essentially creating two new const variables and storing separate parts of our object in them. The rest operator tells the script to put any other not explicitly defined property in the last variable. So all we have to do is destructure all the properties we don’t want — a — so we are left with just the properties we do want stored in our last variable — noA.</p><blockquote>“Perfection is achieved … when there is nothing left to take away.” — Antoine de Saint Exupéry</blockquote><p>What’s especially great about this pattern is, unlike delete, we aren’t mutating the original object, myObject, nor are we removing the reference a, so we can rest assured we haven’t accidentally broken something that is using myObject or a.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38a3ecffe90" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90">Use ES7 Object Rest Operator to Omit Properties</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your React Components Pretty ]]></title>
            <link>https://medium.com/walmartglobaltech/make-your-react-components-pretty-a1ae4ec0f56e?source=rss-6829485f4781------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ae4ec0f56e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jsx]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Mark Brouch]]></dc:creator>
            <pubDate>Tue, 27 Sep 2016 20:34:23 GMT</pubDate>
            <atom:updated>2016-09-29T22:35:15.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-U7Fy39j8YCrLqsooTIKzQ.png" /><figcaption>I took this picture. With my phone. Art.</figcaption></figure><p>At <a href="http://www.walmartlabs.com/">Walmart Labs</a> we do a lot of peer code reviews, which is great because I get to see all sorts of clever ways to write React components from a variety of talented engineers. In this post I’ll share five of my favorite patterns and shortcuts.</p><p>But first…</p><h4>Why Pretty Code Is Better</h4><p>There’s more than one way to skin a cat, and more than one way to write a React component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*R091Ifwl9oeikb3v1rsG1w.png" /></figure><p>However, just because you <em>can</em> write a component any way you see fit doesn’t mean you <em>should</em>. <strong>Code is meant to be read by humans</strong>; computers just interpret whatever jumble of characters you throw at them. 🤖</p><p>Your developer peers will thank you if you make your components as pretty on the inside as they are on the outside.</p><p>Pretty components…</p><ul><li>💡 are <strong>easy to understand</strong> even without comments</li><li>🚀 can be even <strong>more performant</strong> than clunky code</li><li>🐛 increase the chances of <strong>catching bugs</strong> before they reach QA</li><li>📝 are <strong>concise</strong> and say a lot with a little</li></ul><blockquote>“Less is more.”</blockquote><blockquote>— Mies van der Rohe</blockquote><h3>1. The Stateless Functional Component (SFC)</h3><p>My favorite React component optimization, which is often overlooked, is the Stateless Functional Component, or SFC for short. I love SFCs because they greatly reduce the amount of baggage that comes with extending the React Component class and will offer** performance advantages as an added bonus!</p><p>Basically, the SFC will make your application fast and look great doing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DTpcI6WC_VDpIU5BbNZYEQ.png" /><figcaption>The Batmobile is an example of a Stateless Functional Component.</figcaption></figure><p>**Under the hood, SFCs just get wrapped in a simple Component with a sole render function, but this pattern will soon be able to benefit from additional optimizations:</p><blockquote>In the future, we’ll also be able to make performance optimizations specific to [SFCs] by avoiding unnecessary checks and memory allocations.</blockquote><blockquote>— Ben Alpert, <a href="https://facebook.github.io/react/blog/2015/09/10/react-v0.14-rc1.html#stateless-function-components">React Blog</a></blockquote><h4>A Practical Example</h4><p>Let’s take a look at how an SFC can greatly reduce the amount of code it takes to write the simple Related Search component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*8qp0jyX7GK_Oimlvc2leeA.png" /></figure><p>Even as a traditional React.Component extension, it doesn’t take much to display a list of related searches:</p><pre>export default class RelatedSearch extends React.Component {<br>  constructor(props) {<br>    super(props);</pre><pre>    this._handleClick = this._handleClick.bind(this);<br>  }</pre><pre>  _handleClick(suggestedUrl, event) {<br>    event.preventDefault();<br>    this.props.onClick(suggestedUrl);<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;section className=&quot;related-search-container&quot;&gt;<br>        &lt;h1 className=&quot;related-search-title&quot;&gt;Related Searches:&lt;/h1&gt;<br>        &lt;Layout x-small={2} small={3} medium={4} padded={true}&gt;<br>          {this.props.relatedQueries.map((query, index) =&gt;<br>            &lt;Link<br>              className=&quot;related-search-link&quot;<br>              onClick={(event) =&gt;<br>                this._handleClick(query.searchQuery, event)}<br>              key={index}&gt;<br>              {query.searchText}<br>            &lt;/Link&gt;<br>          )}<br>        &lt;/Layout&gt;<br>      &lt;/section&gt;<br>    );<br>  }<br>}</pre><p>The SFC alternative, however, offers a <strong>29% lines of code savings</strong>!</p><pre>const _handleClick(suggestedUrl, onClick, event) =&gt; {<br>  event.preventDefault();<br>  onClick(suggestedUrl);<br>};</pre><pre>const RelatedSearch = ({ relatedQueries, onClick }) =&gt;<br>  &lt;section className=&quot;related-search-container&quot;&gt;<br>    &lt;h1 className=&quot;related-search-title&quot;&gt;Related Searches:&lt;/h1&gt;<br>    &lt;Layout x-small={2} small={3} medium={4} padded={true}&gt;<br>      {relatedQueries.map((query, index) =&gt;<br>        &lt;Link<br>          className=&quot;related-search-link&quot;<br>          onClick={(event) =&gt;<br>            _handleClick(query.searchQuery, onClick, event)}<br>          key={index}&gt;<br>          {query.searchText}<br>        &lt;/Link&gt;<br>      )}<br>    &lt;/Layout&gt;<br>  &lt;/section&gt;</pre><pre>export default RelatedSearch;</pre><p>This amazing reduction in code is accomplished primarily in two ways, stemming from the absence of an ES2015 Class extension:</p><ul><li>No constructor (5 LOC)</li><li>Concise render statement using arrow syntax (4 LOC)</li></ul><p>What’s really great about the SFC, however, is the vastly improved readability. First of all, <strong>SFCs represent </strong><a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.5sgngec83"><strong>Pure Components</strong></a><strong> in the best way possible</strong> by being hyper-focused on returning just the JSX for the component. Removing the constructor, which is no longer needed, and refactoring the <em>_handleClick()</em> function outside of the component also aids in readability as concerns are more clearly separated.</p><p>One of my favorite parts of the SFC is how props are clearly defined right up top in the function args list using ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring">Object Destructuring</a> syntax:</p><pre>const RelatedSearch = (<strong>{ relatedQueries, onClick }</strong>) =&gt;</pre><p>This is both a handy place to see all of the props the component is receiving at a quick glance as well as a way to do away with referencing <em>this.props</em> all over the place, making the code more easily read overall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*jlmj_CbYXqUfw7AIFXFIhw.png" /></figure><h4>When Can SFCs Be Used?</h4><p>Probably the best part about SFCs is that <strong>they can be used just about anywhere a Pure Component can be used</strong>. At Walmart Labs, we use Redux to manage the state of our application, which means almost all of our components are candidates for being SFCs.</p><p>There are, however, two instances where a stateless component cannot be a SFC:</p><ul><li>When a component lifecycle method is needed</li><li>When refs are used</li></ul><p>These two instances are fairly uncommon though, and often can be avoided altogether with careful architecture and planning.</p><h3>2. Conditional Components</h3><p>JSX does not allow for if statements, so to avoid having to refactor code into submodules just to use conditional logic, try the ternary instead:</p><pre>render() {<br>  &lt;div class=&quot;search-results-container&quot;&gt;<br>    {this.props.isGrid<br>      ? &lt;SearchResultsGrid /&gt;<br>      : &lt;SearchResultsList /&gt;}<br>  &lt;/div&gt;<br>}</pre><p>This expression is awesome at returning one component or another if a condition is met or not met. However, the ternary might not be the best option for cases where a component should either be rendered or not:</p><pre>render() {<br>  &lt;div class=&quot;search-results-list&quot;&gt;<br>    {this.props.isSoftSort<br>      ? &lt;SoftSortBanner /&gt;<br>      : null<br>    }<br>  &lt;/div&gt;<br>}</pre><p>This works, but it’s like telling React to “Render this component, or else!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*7cAgXhCHZndyCJKWc5ZJ_w.png" /></figure><p>A more semantic and concise approach is by using the logical AND double ampersand to return the conditional component or false:</p><pre>render() {<br>  &lt;div class=&quot;search-results-list&quot;&gt;<br>    {!!this.props.isSoftSort &amp;&amp; &lt;SoftSortBanner /&gt;}<br>  &lt;/div&gt;<br>}</pre><p>This is, of course up to personal preference and some people prefer the ternary approach for any conditional component.</p><p><em>Edit — In a previous version of this post I left out the boolean cast </em>!!<em> from the left side operand, which is dangerous because some falsey values like </em>zero<em> may be unintentionally rendered by React. Always cast your left side operand when using </em>&amp;&amp;<em>. Thanks to Reddit users </em><a href="https://www.reddit.com/r/reactjs/comments/54uez2/heres_5_useful_patterns_to_make_your_component/d859jq2"><em>miketa1957</em></a><em>, </em><a href="https://www.reddit.com/r/reactjs/comments/54uez2/heres_5_useful_patterns_to_make_your_component/d85aufz"><em>HumansAreDumb</em></a><em>, and </em><a href="https://www.reddit.com/r/reactjs/comments/54uez2/heres_5_useful_patterns_to_make_your_component/d85jmfm"><em>alexbarrett</em></a><em> for pointing this out.</em></p><h3>3. Arrow Syntax in React and Redux</h3><p>ES2015 is full of nifty syntax shortcuts, my favorite of which is the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow notation</a>. These are especially great when writing components, but I often see them used short of their full potential:</p><pre>const SoftSort = ({ hardSortUrl, sortByName, onClick }) =&gt; {<br>  return (<br>    &lt;div className=&quot;SearchInfoMessage&quot;&gt;<br>      Showing results sorted by both Relevance and {sortByName}.<br>      &lt;Link<br>        href={`?${hardSortUrl}`}<br>        onClick={(ev) =&gt; onClick(ev, hardSortUrl)}&gt;<br>        Sort results by {sortByName} only<br>      &lt;/Link&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>All this function does is return JSX, so we can be even more concise:</p><pre>const SoftSort = ({ hardSortUrl, sortByName, onClick }) =&gt;<br>  &lt;div className=&quot;SearchInfoMessage&quot;&gt;<br>    Showing results sorted by both Relevance and {sortByName}.<br>    &lt;Link<br>      href={`?${hardSortUrl}`}<br>      onClick={(ev) =&gt; onClick(ev, hardSortUrl)}&gt;<br>      Sort results by {sortByName} only<br>    &lt;/Link&gt;<br>  &lt;/div&gt;</pre><p>That’s a 25% reduction in lines of code — now that’s turning it up to 11!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*ZqsKC6SGQ0dh7_AOAYTgow.png" /><figcaption>Use Arrow functions the way they were meant to be!</figcaption></figure><p>Another place I often see Arrow functions not living up to their full potential is in Redux <em>mapStateToProps</em> functions:</p><pre>const mapStateToProps = ({isLoading}) =&gt; {<br>  return ({<br>    loading: isLoading,<br>  });<br>};</pre><p>Careful here though, when returning an Object, you’ll have to wrap it in parentheses:</p><pre>const mapStateToProps = ({isLoading}) =&gt; ({<br>  loading: isLoading<br>});</pre><p><em>Edit — Thanks </em><a href="https://medium.com/u/14bb25afc42b"><em>Victor Storozhenko</em></a><em> for pointing out the Object Destructuring improvement in this example.</em></p><p>The point of optimizing Arrow functions is to <strong>improve readability by focusing on just the important parts of the function</strong> and removing the background noise of unnecessary return statements and brackets.</p><h3>4. Say What You Mean With Object Destructuring and Spread Attributes</h3><p>Large components often suffer from <strong><em>this.props</em> syndrome</strong>. That is to say, you see the phrase <em>this.props</em> all over the place, which unfortunately detracts from readability by acting as a source of extra noise. Fortunately, with ES2015 Object Destructuring we have a way to concisely write our props in our JSX. Take this example of a Product Price component which has a lot of props to render:</p><pre>render() {<br>  return (<br>    &lt;ProductPrice<br>      hidePriceFulfillmentDisplay=<br>       {this.props.hidePriceFulfillmentDisplay}<br>      primaryOffer={this.props.primaryOffer}<br>      productType={this.props.productType}<br>      productPageUrl={this.props.productPageUrl}<br>      inventory={this.props.inventory}<br>      submapType={this.props.submapType}<br>      ppu={this.props.ppu}<br>      isLoggedIn={this.props.isLoggedIn}<br>      gridView={this.props.isGridView}<br>    /&gt;<br>  );<br>}</pre><p>Wow, that’s a lot of <em>this.props</em>! Here’s a way to cut down on <em>this.props</em> noise:</p><pre>render() {<br>  const {<br>    hidePriceFulfillmentDisplay,<br>    primaryOffer,<br>    productType,<br>    productPageUrl,<br>    inventory,<br>    submapType,<br>    ppu,<br>    isLoggedIn,<br>    gridView<br>  } = this.props;</pre><pre>  return (<br>    &lt;ProductPrice<br>      hidePriceFulfillmentDisplay={hidePriceFulfillmentDisplay}<br>      primaryOffer={primaryOffer}<br>      productType={productType}<br>      productPageUrl={productPageUrl}<br>      inventory={inventory}<br>      submapType={submapType}<br>      ppu={ppu}<br>      isLoggedIn={isLoggedIn}<br>      gridView={isGridView}<br>    /&gt;<br>  );<br>}</pre><p>This adds a few lines of code, but it also makes our code much easier to read and <strong>clearly points out which props we are using in the component</strong>. This makes sense to do in a large component where the same props might be used multiple times and in several subcomponents, but in this simple example we can use <a href="https://facebook.github.io/react/docs/jsx-spread.html#spread-attributes">Spread Attributes</a> for a super shortcut:</p><pre>render() {<br>  const props = this.props;<br>  return &lt;ProductPrice {...props} /&gt;<br>}</pre><p>Stateless Functional Components (as mentioned earlier) make great use of Object Destructuring, since they receive props as an arg:</p><pre>const ProductPrice = ({<br>  hidePriceFulfillmentDisplay,<br>  primaryOffer,<br>  productType,<br>  productPageUrl,<br>  inventory,<br>  submapType,<br>  ppu,<br>  isLoggedIn,<br>  gridView<br>}) =&gt;<br>  &lt;ProductPrice<br>    hidePriceFulfillmentDisplay={hidePriceFulfillmentDisplay}<br>    primaryOffer={primaryOffer}<br>    productType={productType}<br>    productPageUrl={productPageUrl}<br>    inventory={inventory}<br>    submapType={submapType}<br>    ppu={ppu}<br>    isLoggedIn={isLoggedIn}<br>    gridView={isGridView}<br>  /&gt;</pre><h3>5. Method Definition Shorthand</h3><p>This trick might not be incredibly useful, but it sure is pretty. 💅</p><p>Whenever you are writing methods in an object, you can use the ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">Method Definition Shorthand</a> instead of the boring old ES5 way of doing things. This is especially handy in <em>defaultProps</em> declarations:</p><pre>Link.defaultProps = {<br>  onClick(event) {<br>    event.preventDefault();<br>    Logger.log(event);<br>  }<br>};</pre><p>Plus, if you just want to set a default no-op method, it’s super easy:</p><pre>ProductRating.defaultProps = {<br>  onStarsClick() {}<br>};</pre><h3>In Conclusion</h3><p>I hope these tricks I’ve shared help make your React application a more beautiful place and that you will actively think about how you can make your code prettier. Remember, <strong>beautiful code does a lot without saying much</strong>.</p><blockquote>“Speak softly and carry a big stick.”</blockquote><blockquote>— Theodore Roosevelt</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ae4ec0f56e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/make-your-react-components-pretty-a1ae4ec0f56e">Make Your React Components Pretty 💅</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edit live sites on the fly with Browsersync!]]></title>
            <link>https://medium.com/@markbrouch/edit-live-sites-on-the-fly-with-browsersync-426690dac3f1?source=rss-6829485f4781------2</link>
            <guid isPermaLink="false">https://medium.com/p/426690dac3f1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[browsersync]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mark Brouch]]></dc:creator>
            <pubDate>Thu, 17 Mar 2016 23:12:24 GMT</pubDate>
            <atom:updated>2016-03-17T23:12:24.898Z</atom:updated>
            <content:encoded><![CDATA[<p>Scenario: It’s Monday afternoon, you just received a request from the new client to fix a glaring JS bug on their production site, but your red-tape machete has yet to cut through the jungle of bureaucracy far enough to see a working development environment set up. You know this fix will only take an hour to implement once you have the access you need to, you know, <em>actually touch the defective code</em>. If only development was as easy as just developing, right?</p><p>Ok, so maybe your situation isn’t as dramatic as the aforementioned, but you still need a solution that allows you to load a live site and tweak individual assets, be they scripts or styles. If you’re like me, then you like tinkering with changes and see their direct results rather than waiting for the code to stabilize, build, test, deploy, etc. Dev tools get you so far, but <strong>wouldn’t it be great if you could edit certain files on your local machine and see them in the context of the live production site immediately</strong> without worrying about breaking everything in the process?</p><p>Well, it’s your lucky day, because I’m about to show you how to use the amazing <a href="https://www.browsersync.io/">Browsersync</a>’s proxy and rewrite rules features to edit a live site like it was a local development environment! For this example, we’ll be tweaking the Wikipedia homepage, although I’ve used this in the past to quickly work on AEM implementations which can sometimes be difficult to get proper development access to, particularly for front-end development.</p><p>First, we’ll need to set up a new project on our local development machine. I’ll create mine in ‘~/Sites/wikipedia’. From there, we’ll create a subdirectory called ‘assets’ to stuff our custom JS and CSS files. Next, navigate to your project root (‘~/Sites/wikipedia’) and initialize a new NPM package. We’ll be installing some Node modules and this is the easiest way to save our configuration. Use the commands below to set up the package and install the Browsersync dependency we will be needing. Since we don’t plan on publishing this Node module, the details of the ‘npm init’ prompt aren’t important. Later you can go back and fill the rest of the generated package.json file out if you want to build out a full project, but that’s not the point of this article.</p><pre>cd ~/Sites/wikipedia<br>npm init<br>npm install --save browser-sync</pre><p>Next, we will create a Browsersync file that will be run by Node to create a local Browsersync server that proxies the live site and substitutes whatever local assets we want. Make a new file called ‘bs.js’ in the project root. We’ll need to include the Browsersync package we just installed here. Next, we’ll invoke the browserSync module and proxy Wikipedia:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/798072d6608bf4efc3439c10a63ff085/href">https://medium.com/media/798072d6608bf4efc3439c10a63ff085/href</a></iframe><p>With this code we are able to run our Browsersync server which will display Wikipedia.org from our localhost on port 3000. From the root of the project, run the command ‘node bs’ and a browser window will open ‘https://localhost:3000’ displaying the Wikipedia website. You can even access the Browsersync control panel from port 3001, neat!</p><p>However, what we really want to do is serve local assets in place of their remote counterparts on Wikipedia’s servers. To do this we need to add a few more lines of code to our ‘bs.js’ file.</p><p>If you inspect the page at <a href="https://localhost:3000/">https://localhost:3000</a> and open the network tab you can filter to see all JS files. We are going to modify the main page JS file, which is named something like ‘index-####.js’. Open that file in chrome and copy its contents to a file on your local development machine called ‘/assets/js/index.js’. You’ll notice that Wikipedia has wisely minified this file, but we’ll assume if you are using this process on your own site that you would have access to an unminified version of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Hv_bErORRjS69U_6MTwNw.png" /></figure><p>Now that we have a local JS file, we can tell Browsersync to serve it in place of the remote file using rewrite rules. Add the following config options in bs.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6084614958be27b8fea1db810ba70c1a/href">https://medium.com/media/6084614958be27b8fea1db810ba70c1a/href</a></iframe><p>The ‘files’ array contains a list of local paths for Browsersync to watch for file changes so it can automagically update the site at <a href="http://localhost:3000/">http://localhost:3000</a> as you develop! The ‘serveStatic’ array contains a list of local paths to serve on <a href="http://localhost:3000.">http://localhost:3000</a> using middleware. If a request matches a file in one of these paths then Browsersync will serve it, otherwise it will forward the request on to the proxied live site. This is what allows us to mix local assets with remote assets.</p><p>The ‘rewriteRules’ array contains a list of rules for replacing certain text strings. We will use it to replace the url of the remote JS file with that of our local. Be sure to change the regular expression to match the path of the remote file you want to replace.</p><p>Now that we’ve configured our Browsersync server to replace the index-6adef12f4f.js with our local index.js file, we can restart the Browsersync server with ‘node bs’. Since we copied the contents of the remote JS file into our local JS file, everything should work as it did before. However, now we can edit the local JS file and see the updates as they would apply to the live site. Try it out by adding a ‘console.log(‘Hello world!’);’ at the top of index.js. Notice that Browsersync detects the change and automatically reloads the browser page with the updated code! For certain types of assets, like CSS or images, Browsersync will inject the changes instead of reloading the page, which is super handy if you’re, say, styling a modal or the 5th page of a form.</p><p>So there you have it, using this method, <strong>we can replace any remote asset with a local version</strong> by adding additional rewrite rules in our Browsersync config file. We can even use these settings in a more sophisticated Browsersync + Gulp configuration that might do even more tasks like compiling Sass and adding autoprefixing and sourcemaps. Check out the <a href="https://www.browsersync.io/docs/recipes/">Browsersync recipes</a> for some ideas on how we might add more tasks.</p><p>A special thanks to <a href="https://github.com/fvsch">Florent Verschelde</a> who created a <a href="https://gist.github.com/fvsch">gist</a> showing how to implement this method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=426690dac3f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>