<?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 Alastair Taft on Medium]]></title>
        <description><![CDATA[Stories by Alastair Taft on Medium]]></description>
        <link>https://medium.com/@alastairtaft?source=rss-18f61befca76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7rEUX3LODUkXtChNPk-i2g.jpeg</url>
            <title>Stories by Alastair Taft on Medium</title>
            <link>https://medium.com/@alastairtaft?source=rss-18f61befca76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:30:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alastairtaft/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[Stop using pointless npm packages]]></title>
            <link>https://alastairtaft.medium.com/stop-using-pointless-npm-packages-91ae89ebaba6?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ae89ebaba6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 01:40:58 GMT</pubDate>
            <atom:updated>2025-08-08T01:40:58.865Z</atom:updated>
            <content:encoded><![CDATA[<p>I wrote about <a href="https://medium.com/@alastairtaft/stop-depending-on-tiny-brittle-packages-63e183d7ddda">this same issue</a> 7 years ago and its still as true today as it was then.</p><p>I recently came across an issue where I wanted to render a fallback UI if my React component threw an error while rendering.</p><p>I remembered there were ErrorBoundary’s so a quick Google lands me on <a href="https://legacy.reactjs.org/docs/error-boundaries.html">the old React docs site</a>, which says these docs are deprecated go to here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7Y4S_yN6ZCxiiyWZqr0Uw.png" /></figure><p>Following the link to the new site it makes a suggestion to use a third party package. The official React docs say use a third party package! Was this snuck in by a Facebook employee wanting to bump their vanity Github metrics?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJQ4_iaxaI8N_kgn0xAqAg.png" /></figure><p>Why would you even? It’s less than 30 lines of code to do exactly the same as this with your own class, here it is:</p><pre>import * as React from &#39;react&#39;<br><br>class ErrorBoundary extends React.Component {<br>  constructor(props) {<br>    super(props)<br>    this.state = { error: null }<br>  }<br><br>  static getDerivedStateFromError(error) {<br>    return { error }<br>  }<br><br>  componentDidCatch(error) {<br>    console.error(error)<br>  }<br><br>  render() {<br>    const { children, fallback, fallbackRender } = this.props<br>    const { error } = this.state<br>    if (!error) {<br>      return children<br>    }<br>    if (fallbackRender)<br>      return fallbackRender({ error })<br>    return fallback<br>  }<br>}<br><br>export default ErrorBoundary</pre><p>Why add a dependency for this? Did we learn nothing from npm supply chain attacks, what if this developer silently publishes an npm update with some spyware baked in?</p><p>It blows my mind that people think, mmm I could write 30 lines of code… no, I’ll instead give a dependency access to my machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*mu4BLtDJCO6rTY04grt7Jg.png" /></figure><p>And look it has over 5 million machines downloading the package weekly? 🤯. What if this dev does something novel out like a <a href="https://en.wikipedia.org/wiki/Npm_left-pad_incident">left-pad</a> incident, maybe that’s 5 million software projects broken or worse silently compromised.</p><p>And 6 major version bumps without any actual code changes, why? Just for the lols of making people upgrade to do the same thing? I don’t get it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuTlIx5R5nMp8Jg_VIYTug.png" /></figure><p>Please take the time to write 30 lines of code. Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ae89ebaba6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generators, they are amazing]]></title>
            <link>https://alastairtaft.medium.com/generators-they-are-amazing-6683b3e032ca?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/6683b3e032ca</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 00:24:28 GMT</pubDate>
            <atom:updated>2025-07-11T13:57:36.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>I love JavaScript generators</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*G4Uzv2SJgapPVM9p0Cp2LQ@2x.jpeg" /></figure><p>What the hell are Generators in JavaScript? You can probably go your professional JS life without ever needing to use them, but they are really cool and I often find myself using them for one particular use case where I think they really shine.</p><p>Search endpoints. Why? They can iterate huge sets of data without blowing up your memory and if you write them the right way they can handle the cursor on your pagination.</p><p>So what are generators? In my own words, they allow you to asyncly iterate over all the complexities of fetching items from your database so you can keep your code really clean.</p><p>Let’s say you have 1 million records that you’re writing a search endpoint for. The generator allows you to keep your data fetching code seperate from your route logic code so you don’t need to concern yourself with accessing the database in your route logic, simply ask for as many records as you need and get back a cursor to start iterating on the next set of records.</p><p>It makes it impossible for you to do things like fetch 1 million records from the database and then try and do an array slice on records 100 to 150, which of course might look like it will work when you don’t have much data but at scale your app will grind to a halt.</p><p>Here’s simple search route code that gets the first 20 records from provided search text.</p><pre>var searchItemsRoute = async function({ searchText, limit = 20 }){<br>  var iterator = createSearchItemsIterator({<br>    searchText,<br>  })<br>  var items = []<br>  do {<br>    if (limit == 0)<br>      break;<br>    var { value, done } = await iterator.next()<br>    if (done){<br>      break;<br>    }<br>    items.push(value)<br>    limit--<br>  } while (true)<br>  return { items }<br>}</pre><p>This nicely let’s you worry about how your search is going to work inside the iterator, all we care about here is that we’re asking for 20 records for the search. There’s no pagination yet.</p><p>I won’t go into detail on the generator logic, in here you’d make calls to your database, all databases will have a way of paginating your queries in an efficient way.</p><pre>const createSearchItemsIterator = async function*({ searchText }){<br>  var items = await searchItemsFromDatabase({ <br>    searchText,<br>  })<br>  for (var item of items){<br>    yield item<br>  }<br>}</pre><p>This is all simple enough but it won’t handle pagination.</p><p>Let’s add some pagination to our iterator, we’ll make it support passing in and returning a cursor. The way a works is it’s telling our iterator to only start getting records after our cursor.</p><p>Most database methods have a way of getting records after a point, I generally use DynamoDB and you can pass in a LastEvaluatedKey which is the record key, but other database work differently, but I’ll be using that concept here, i.e. using the record key as the cursor.</p><pre>const createSearchItemsIterator = async function*({ searchText, cursor }){<br>  var items = await searchItemsFromDatabase({ <br>    searchText,<br>    LastEvaluatedKey: cursor,<br>  })<br>  for (var item of items){<br>    yield { item, cursor: { id: item.id } }<br>  }<br>}</pre><p>Now we need to update our route endpoint to use our pagination.</p><pre>var searchItemsRoute = async function({ searchText, limit = 20, cursor }){<br>  if (cursor){<br>    cursor = JSON.parse(decodeURIComponent(cursor))<br>  }  <br>  var iterator = createSearchItemsIterator({<br>    searchText,<br>    cursor,<br>  })<br>  var items = []<br>  var lastCursor<br>  do {<br>    if (limit == 0)<br>      break;<br>    var { value, done } = await iterator.next()<br>    if (done){<br>      lastCursor = undefined<br>      break;<br>    }<br>    lastCursor = value.cursor<br>    items.push(value.item)<br>    limit--<br>  } while (true)<br>  return { <br>    items,<br>    // Here we&#39;re converting the cursor to a URL safe string so that it can<br>    // be used in the query string on our route endpoint<br>    lastCursor ? encodeURIComponent(JSON.stringify(lastCursor)) : undefined<br>  }<br>}</pre><p>That’s it, a simple generator based search endpoint. Of course there’s much more you can do and you can make it as complex as you’d like, but I love the concept of splitting out your database search logic from your route code, as searching the database can get messy and there’s no need to make your route code complex because of it and if you structure it this way, there’s no way you can run out of memory on large data sets.</p><p>You might want to add in a bit of handling too, i.e. I didn’t check that my limit was a number, and I’m also not pruning the data fetched directly from the database before returning it to the world. You could also add an upper limit on the amount of records that can be requested as to ensure someone can’t crash your endpoint by iterating over too many records.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6683b3e032ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Pivotal Tracker’s ticket ids]]></title>
            <link>https://alastairtaft.medium.com/improving-pivotal-trackers-ticket-ids-33289f875152?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/33289f875152</guid>
            <category><![CDATA[pivotal-tracker]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Sun, 08 Sep 2019 23:24:52 GMT</pubDate>
            <atom:updated>2019-09-08T23:24:52.568Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-lAd7r7Gl79uI8CYPtRRg.jpeg" /><figcaption>Pivotal Tracker’s dashboard</figcaption></figure><p>Pivotals tracking ids suck, they are 9 digit long ids that make it really hard for tickets to be talking points. Let’s fix that.</p><p><strong>TLDR If you want auto incrementing easy to remember ticket ids, </strong><a href="https://github.com/AlastairTaft/pivotal-friendly-numbers"><strong>use Pivotal’s webhooks and api</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*d3M_0I-BJqFubUtLWCksCw.gif" /></figure><p>We recently decided to trial Pivotal Tracker, making the switch from Jira. I think it&#39;s great but one thing that does suck is not having nice ticket ids. And it makes talking about tickets very difficult, no one wants to read off a 9 digit number like #168307586 in stand up.</p><p>In Jira the tickets would start at 1 and increment every time you create a new issue. In our case we’d have tickets like PAD-1847 or PAD-677. This method also has the added benefit of knowing roughly how old an issue. If you have 2000 tickets and the number is 500, you know it’s very old.</p><h4>How to do this in Pivotal?</h4><p>Fortunately Pivotal has <a href="https://www.pivotaltracker.com/help/api/">an awesome api</a> and <a href="https://www.pivotaltracker.com/help/articles/activity_webhook/">webhook support</a>. So it shouldn’t be too difficult to put a nice ticket number in the ticket name every time one is created. It would go something like this</p><ol><li>User creates ticket</li><li>Webhook is pinged</li><li>Bot account puts a nice ticket number in the name</li></ol><p>And that’s what we did.</p><p>There’s a slight delay while it does the round trip with the webhook and then an update. But it’s good enough for us.</p><h4>Other steps</h4><p>We ensured the nice ticket name is set on update too.</p><p>We added our own database to the mix to track incrementing ids, if you don’t care about incrementing ids and you want to keep the solution stateless you could probably convert the last 5 digits of the pivotal id to base -36. So #168307586 would become #5UQ, #168305907 would be #4K3, etc.</p><p>The last 5 digits would likely be sufficient to ensure you probably won’t get any duplicates</p><p>Working solution can be found over <a href="https://github.com/AlastairTaft/pivotal-friendly-numbers">on my Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33289f875152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 Imports are confusing but great]]></title>
            <link>https://alastairtaft.medium.com/es6-imports-are-confusing-but-great-a9e974f5aeef?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e974f5aeef</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Fri, 07 Sep 2018 01:51:14 GMT</pubDate>
            <atom:updated>2018-09-07T02:12:39.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Just noticed this on the BugSnag setup tutorial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYIqZ8WqtGzjEox1sdtpMg.png" /></figure><p>From my understanding that’s not how imports work. The cool thing about imports is, even though they are more restrictive, they all happen before any code is executed which is really powerful. It means we can statically analyses code and make some really good optimisations.</p><p>Before import we had require which was good for its time but posed a problem. Let’s say we had the following code.</p><pre>// foo.js<br>module.exports = {<br>  foo: &#39;bar&#39;,<br>  someOtherVar: &#39;that is never needed&#39;,<br>}</pre><pre>// entry.js<br>var myConditionalModule = &#39;more foo&#39;<br>if (Math.random() &lt; 0.5){<br>  myConditionalModule = require(&#39;foo.js&#39;)<br>}<br>console.log(myConditionalModule.foo)</pre><p>If we run <em>entry.js</em>, because we are requiring a module at runtime we don’t know before execution if we’re going to need to require that <em>foo.js</em> module or not.</p><p>So if we were to minify the code we can’t really flatten out the script easily, it would look something like this.</p><pre>// Our foo.js module<br>function module_foo(module){<br>  module.exports = {<br>    foo: &#39;bar&#39;,<br>    someOtherVar: &#39;that is never needed&#39;,<br>  }<br>}</pre><pre>// Some &#39;require&#39; boilerplate, its probably not correct, but it<br>// makes the point<br>function require(moduleFunc){<br>  var module = { exports: {} }<br>  moduleFunc(module)  <br>  return module.exports<br>}</pre><pre>var myConditionalModule = &#39;more foo&#39;<br>if (Math.random() &lt; 0.5){<br>  myConditionalModule = require(module_foo)<br>  console.log(myConditionalModule.foo)<br>}</pre><p>You can see its quite hard to understand what’s going on and that we had to add some require() boilerplate to make it work.</p><p>Now if we instead enforced no runtime module require’s, our code becomes a lot easier to analyse. We could rewrite the first block of code like this.</p><pre>// foo.js<br>module.exports = {<br>  foo: &#39;bar&#39;,<br>  someOtherVar: &#39;that is never needed&#39;,<br>}</pre><pre>// entry.js <br>// Do all the module importing before any code<br>var myConditionalModule = require(&#39;foo.js&#39;)<br>if (Math.random() &lt; 0.5){<br>  console.log(myConditionalModule.foo)<br>}</pre><p>Notice the require() here is being used in the same way imports work, i.e. before any code is ran.</p><p>Now if we were to flatten the code</p><pre>// Do all the module importing before any code<br>var myConditionalModule = {<br>  foo: &#39;bar&#39;,<br>  someOtherVar: &#39;that is never needed&#39;,<br>}<br>if (Math.random() &lt; 0.5){<br>  console.log(myConditionalModule.foo)<br>}</pre><p>Suddenly it becomes a lot easier for the compiler to understand and it could then optimise it by stripping out the someOtherVar because now it can tell that that variable is never used.</p><p>Furthermore when you write stuff like</p><pre><strong>import</strong> bugsnag <strong>from</strong> &#39;bugsnag-js&#39; <br><strong>const</strong> bugsnagClient = bugsnag(&#39;f1c7dcdc29e23c8f2832925f3b908b54&#39;)  </pre><pre><strong>import</strong> ReactDOM <strong>from</strong> &#39;react-dom&#39; <br><strong>import</strong> React <strong>from</strong> &#39;react&#39; <br><strong>import</strong> createPlugin <strong>from</strong> &#39;bugsnag-react&#39;</pre><p>I think what actually happens is this</p><pre><strong>import</strong> bugsnag <strong>from</strong> &#39;bugsnag-js&#39; <br><strong>import</strong> ReactDOM <strong>from</strong> &#39;react-dom&#39; <br><strong>import</strong> React <strong>from</strong> &#39;react&#39; <br><strong>import</strong> createPlugin <strong>from</strong> &#39;bugsnag-react&#39;</pre><pre><strong>const</strong> bugsnagClient = bugsnag(&#39;f1c7dcdc29e23c8f2832925f3b908b54&#39;)</pre><p>That’s my understanding, now patiently waiting for someone to tell me it&#39;s all wrong.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e974f5aeef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I prefer var over let and const]]></title>
            <link>https://alastairtaft.medium.com/i-prefer-var-over-let-and-const-9ba32621f0a7?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ba32621f0a7</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es2015]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Wed, 27 Jun 2018 16:41:19 GMT</pubDate>
            <atom:updated>2018-06-27T16:54:14.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAnvvyR_SU6jAYBUBQARbw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/nXOB-wh4Oyc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Khachik Simonian</a> on <a href="https://unsplash.com/search/photos/beach?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I know I’m in the minority here, everywhere I turn there’s an article telling me to drop<strong><em>`var` </em></strong>and use<strong><em>`let`</em></strong> and <strong><em>`const` </em></strong>exclusively.</p><p>But I like <strong><em>`var`</em></strong>. Why? Mainly because I love functional scope, it feels so natural. One thing I like doing, is being able to write code like this.</p><pre>if (myCondition == true)<br>  var myProp = 123<br>return {<br>  myProp<br>}</pre><p>If you winced at the above then you probably love block scope and having to declare your variable every time before you use it, you probably also love adding thousands of unnecessary semi-colons to the end of every line too, but I digress...</p><p>Writing the above is quick and still very readable and, for those familiar with React, really useful when writing lots of conditions in mapStateToProps functions as part of redux’sconnect.</p><p>I can use recursion and functional scope my way. For example here’s some code that traverses a ‘schema’ object looking for a field that satisfies a condition and if found it returns the field together with a new version of the schema without the field. You’ll notice its using some ‘hoisting’ too.</p><pre>function extractFieldByCondition(condition, schema){<br>  <br>  var foundField = null</pre><pre>  processSchema(screenState)</pre><pre>  return {<br>    field: foundField,<br>    screenState,<br>  }</pre><pre>  function processSchema(){ <br>    var foundFieldKey = schema[&#39;layout&#39;].find(processField)<br>    if (foundFieldKey){<br>      schema = Object.assign({}, schema)<br>      schema[&#39;layout&#39;] = schema[&#39;layout&#39;].slice(0)<br>      schema[&#39;layout&#39;].splice(<br>        schema[&#39;layout&#39;].indexOf(foundFieldKey), 1)<br>    }<br>  }</pre><pre>  function processField(fieldKey){<br>    var field = schema[fieldKey]<br>    if (condition(fieldKey)){<br>      schema = Object.assign({}, schema)<br>      delete schema[fieldKey] <br>      foundField = field<br>      return true<br>    }<br>  }<br>}</pre><p>That code wouldn’t work if I declared foundField with <strong><em>`let`</em></strong> or <strong><em>`const`</em></strong>. Maybe I could rewrite it so it would. There’s good arguments to be made on both sides but isn’t that the beauty of JavaScript, I can code in my own arguably elegant way, why are we so quick to throw away some of the tools that make JavaScript so flexible? We may as well go back to writing C#</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ba32621f0a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing my React context menu]]></title>
            <link>https://alastairtaft.medium.com/introducing-my-react-context-menu-819a05765ef3?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/819a05765ef3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Thu, 21 Jun 2018 14:34:16 GMT</pubDate>
            <atom:updated>2018-06-21T14:34:16.952Z</atom:updated>
            <content:encoded><![CDATA[<p>I was in need of a simple context menu. After some quick Googling I was amazed at how many bad, popular, bloated solutions were out there. So I knocked up my own without any dependencies and a simple api that only needed 100 lines of code (including comments).</p><p><a href="https://github.com/AlastairTaft/contextmenu">Check it out</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819a05765ef3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My view on the state of CSS in JS]]></title>
            <link>https://alastairtaft.medium.com/my-view-on-the-state-of-css-in-js-543b79d48e00?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/543b79d48e00</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css-animation]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 01:33:14 GMT</pubDate>
            <atom:updated>2018-03-09T01:33:14.454Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently volunteered to give a talk at a local developer meetup in Tasmania, <a href="http://web.dev42.co/">Web Dev 42</a>.</p><p>I whipped up a few slides you can check out over at <a href="http://slides.com/allytaft/css-in-jss">slides.com</a> if you’re interested</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=543b79d48e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop depending on tiny brittle packages]]></title>
            <link>https://alastairtaft.medium.com/stop-depending-on-tiny-brittle-packages-63e183d7ddda?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/63e183d7ddda</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 03:10:42 GMT</pubDate>
            <atom:updated>2018-02-02T03:21:54.898Z</atom:updated>
            <content:encoded><![CDATA[<p>Warning, personal rant up ahead.</p><p>I recently just added Google’s <a href="https://www.google.com/recaptcha/intro/android.html#">reCAPTCHA</a> to a react app. It was a slight bit of work as reCAPTCHA isn’t built to integrate nicely with React, I had to break out the regular DOM JS stuff that React hides away from you.</p><p>So after looking at the docs it seems I needed to load the reCAPTCHA script and then render the captcha once the script’s done loading, doesn’t sound to hard, and it isn’t. After a bit of thought I put together a simple component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSlSUnf-HNdE-80fNx6lmg.png" /><figcaption>Captcha component</figcaption></figure><p>Now, it’s not that pretty but it does the job. I can call it like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wtqqt00ksADNTT31GBwN1Q.png" /><figcaption>Captcha usage</figcaption></figure><p>Out of interest I looked on npm to see if there’s a package for this and if they’d solved it in a better way.<a href="https://www.npmjs.com/package/react-recaptcha"> First hit (react-recaptcha) </a>with 35k monthly downloads needs you to put the google script in the head of your html document, not very React component encapsulation friendly. In the code it also uses a setInterval to check for when the captcha script has loaded. All of which is very hacky, why not just load the script and listen to the load event? Simple.</p><p>The second npm package I found didn’t fare much better, <a href="https://www.npmjs.com/package/react-google-recaptcha">react-google-recaptcha</a> with 70k monthly downloads has a whole cludge of seemingly over engineered code. What’s worse is it depends on another package whose sole job is to load a script, it manages to do this with a whopping, 200 lines of code. I mean, what’s so difficult about doing?</p><pre>var script = document.createElement(&#39;script&#39;)<br>script.src = &quot;my-awesome-script.js&quot;<br>document.body.appendChild(script)</pre><p>What’s my point? I guess I’m just surprised how many people are depending on these seemingly brittle implementations, why not vet your dependencies or build something small yourself.</p><p>/rantover</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63e183d7ddda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Google’s closure library with webpack]]></title>
            <link>https://alastairtaft.medium.com/using-googles-closure-library-with-webpack-b944e2a4be3a?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/b944e2a4be3a</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[closure-compiler]]></category>
            <category><![CDATA[library-closures]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Mon, 18 Sep 2017 15:07:49 GMT</pubDate>
            <atom:updated>2017-09-24T14:29:30.151Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the weekend I participated in a hackathon, we decided to build a web app that would help keep your daily tasks inline with your big goals.</p><p><strong>TLDR;</strong> To use the <a href="https://developers.google.com/closure/library/">closure library</a> with webpack, try <a href="https://github.com/AlastairTaft/closure-library-starter">this starter project</a>.</p><p>Caveat: Webpack + closure compiler in ADVANCED mode isn’t very good at removing dead code.</p><p>As the sole developer I took the project as far as I could in the space of the weekend. It was built using React, and relies heavily on dragging and dropping bite sized tasks which we nicknamed “actionables”. If you’re interested, checkout <a href="https://github.com/AlastairTaft/uhack2017">this</a> repo repo for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEbJvltnslRrdEzjWQ7Img.jpeg" /></figure><p>I plan on taking the project a little further by building out a polished app. I need it to work well on both mobile and desktop, which meant relooking at the tech stack I picked over the weekend. I was heavily relying on <a href="https://github.com/react-dnd/react-dnd">react dnd</a> which upon further inspection does not seem to support mobile, there exists a <a href="https://github.com/yahoo/react-dnd-touch-backend">third party implementation</a> but after trying it out it didn’t seem to work at all, and there’s not been much activity on the repo recently. For this reason I don’t want to be locked into that library.</p><p>There seems to be a trend with React libraries not having much touch support. <a href="https://draftjs.org/">Draft-js</a> is another awesome library that doesn’t work on chrome mobile. I guess mobile web support isn’t high up on Facebook’s priorities.</p><p>So I thought about building my own simple drag and drop implementation, I realize it will be a lot of work, but at least I can guarantee mobile support and I’ll have more control over where I want to take my app. My gut feeling is that if I chose React to do this I’d be working against it more than with it. Why? React abstracts away the DOM but I’d want to be working with the DOM a lot.</p><p>Which made me think of Google’s closure library. It’s a well tested low level library. I’ve built large interactive apps with it before and they’ve generally been extremely solid. But it’s a huge pain to setup. From what I remember you have to manually configure your dependencies and generate a <em>deps.js</em> file, which then loads other scripts as and when needed. CommonJS and then ES6 modules is a vast improvement and not being able to use this would be a big regression.</p><p>Creating html in closure can be very verbose and tedious to write, something that React’s JSX has been revolutionary in solving. I’d still like to have the syntactic sugar that JSX gives me so it would be great if I can bring JSX to the closure library.</p><h4>Requirements</h4><p>In summary, I want to link CommonJS modules, JSX with the closure library. Which breaks down into this:</p><ul><li>Can load any closure module the commonJS or ES6 modules way, for example var array = require(&#39;goog.array&#39;) or import array from &#39;goog.array&#39;, path could be goog/array or some other variant.</li><li>Can still use JSX for building DOM, as building DOM in native JS is tedious.</li><li>Works with the Google closure library dropped in, i.e. no modifications needed to the closure-library codebase. Because if I had to retro fit every update it would take too much time.</li><li>Works with the closure compiler. May as well take advantage of the powerful closure-compiler as the library works with it out of the box.</li></ul><h4>Using JSX</h4><p>The first thing I thought I’d tackle would be using JSX with closure. Every UI component in closure has a createDom() method that builds the DOM objects. For example here’s what the method looks like for the CheckBox control.</p><pre>goog.ui.Css3ButtonRenderer.prototype.createDom = function(control){<br>  var button = /** @type {goog.ui.Button} */ (control);<br>  var classNames = this.getClassNames(button); <br>  return button.getDomHelper().createDom(<br>    goog.dom.TagName.DIV, {<br>      &#39;class&#39;: goog.ui.INLINE_BLOCK_CLASSNAME + &#39; &#39; <br>        + classNames.join(&#39; &#39;),<br>      &#39;title&#39;: button.getTooltip() || &#39;&#39; <br>    }, <br>    button.getContent()<br>  );<br>};</pre><p>The same thing using JSX looks like</p><pre>goog.ui.Css3ButtonRenderer.prototype.createDom = function(control){<br>  var button = /** @type {goog.ui.Button} */ (control);<br>  var classNames = this.getClassNames(button); <br>  return &lt;div <br>    className={goog.ui.INLINE_BLOCK_CLASSNAME + &#39; &#39; <br>      + classNames.join(&#39; &#39;)}<br>    title={button.getTooltip()}<br>  &gt;<br>    {button.getContent()}<br>  &lt;/div&gt;<br>};</pre><p>Arguably the second one’s easier to write. Either way if I have to build something DOM heavy its nice to have JSX at my disposal.</p><p>A quick Google of JSX tells me that the babel plugin accepts a <a href="https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx#pragma">pragma</a> option, which means we can use Google’s DOM builder instead of React.</p><p>Each Google control instance has a this.dom_ property which conveniently has a createDom method with exactly the same call structure as React.createElement . Therefore switching to using that instead of React is as simple as adding the following webpack plugin.</p><pre>[&quot;transform-react-jsx&quot;, { &quot;pragma&quot;: &quot;this.dom_.createDom&quot; }]</pre><h4>Module loading</h4><p>The next issue is solving the module loading. We do not want to be tide into Google’s module loading, we want to stick with CommonJS / ES6. This is a tricky one to solve because Google uses a goog.provide(&#39;my.module&#39;) method to indicate there’s something to provide and goog.require(&#39;my.module&#39;) to load a module. Given that one file can have multiple goog.provide‘s it doesn’t link up with the CommonJS system so easily. Furthermore it relies on global vars which is why it’s namespaced so verbosely. e.g. for array methods you’d goog.require(&#39;goog.array&#39;) and then start calling it like goog.array.forEach(myArray, () =&gt; doStuff()). If we did this the CommonJS way it isn’t so verbose writing out the namespace each time var array = require(&#39;goog.array&#39;) then array.forEach(myArray, () =&gt; doStuff()).</p><p>To solve the problem I needed to change all the require and provide statements into a way that works with CommonJS. This is something babel could probably solve but I know nothing about building babel plugins. <br>So I fumbled my way through the babel docs and managed to cobble something together that does the job. It’s pretty ugly so I won’t paste it here but you can have a look at the sourcecode if you really want to.</p><p>What it does is convert this</p><pre>goog.provide(&#39;goog.debug.Debug&#39;)</pre><pre>goog.require(&#39;goog.array&#39;)</pre><p>into this</p><pre>module.exports = goog;<br>goog.debug = goog.debug || {};<br>goog.debug.Debug = goog.debug.Debug || {};`</pre><pre>goog.array = require(&quot;goog.array&quot;).array;</pre><p>That’s still not enough to make the modules load without error. In order for all the modules to load correctly the global googvar needed to exist, this is done in the closure library base file. From what I know of closure, the base file functions as a sort of initialization and is intended to be swapped out to initialize different environments which is why I allowed myself to modify this file while still adhering to my requirement of not modding the library itself. I made a few slight adjustments so that the babel’d closure modules now load correctly and was sure to load the custom goog file before loading anything else in my app.</p><p>The next piece of the puzzle is getting paths like goog.array to know where to load the file from. Webpack to the rescue, this is exactly what <a href="https://webpack.js.org/configuration/resolve/#resolve-alias">webpack’s alias config option</a> can do. It works by matching an alias to a file path.</p><p>So I’d need to build a method that maps all the provide statements to the locations of where their files exist on the system. This should be as straightforward as walking over the files and regex’ing to find provide statements.</p><p>Sure enough that’s exactly what I did.</p><pre>/**<br> * Generates an object of aliases so that webpack can resolve<br> */<br>function run(libraryFolder){<br>  var aliases = {}<br>  var files = walkSync(libraryFolder)<br>  files.forEach(f =&gt; {<br>    var content = fs.readFileSync(f, { encoding: &#39;UTF8&#39; })<br>    var namespaces = extractProvides(content)<br>    namespaces.forEach(n =&gt; aliases[n] = f)<br>  })<br>  return aliases<br>}</pre><p>However after testing this my webpack start script was bombing out with a maximum call stack size error caused by the sheer number of aliases needed for the closure library. I worked around the problem by increasing the call stack size on the command line --stack-size=99999.</p><h4>Using the compiler</h4><p>If I’m going to be using the low level closure library I may as well take advantage of it being fully compatible with the closure compiler in advanced mode. Fortunately after googling, someone had already created a <a href="https://github.com/roman01la/webpack-closure-compiler">webpack plugin</a>. But upon running it I ran into loads of compile errors.</p><p>Because webpack wraps the entire bundle in a function, the compiler was complaining about methods that should only be called in the global scope. Namely goog.define. Since the global scope doesn’t need to be used because we’re using CommonJS, I modified my babel plugin to remove these calls.</p><p>It then fell over on the goog.LOCALE variable not existing. I don’t know enough about how this variable works with the compiler to update it accordingly but for my purposes I just added goog.LOCALE = &#39;en_GB&#39; and my bundled compiled just fine.</p><h4>Conclusion</h4><p>The closure library seems to run just fine when loaded through webpack. I love this low level library and plan to use it to develop my Goal-Step app into something further.</p><p><strong>UPDATE:</strong> After some more playing around, webpack is pretty terrible at working with the compiler in advanced mode, it arranges the code in such a way that prevents the compiler from removing a lot of dead code, thus losing a lot of the benefits of the closure compiler.</p><p>After spending the day dissecting webpack’s generated bundle, due to the way modules are loaded a lot of dead code isn’t eliminated. This is because a module is loaded at runtime, i.e. you may execute a bunch of code and then load up a module. This makes sense, but it means the compiler can’t figure out what depends on what and thus doesn’t strip out anything attached to module.exports.</p><p>I ended up dropping webpack and using just the closure compiler, see the <a href="https://github.com/AlastairTaft/closure-library-starter/tree/remove-webpack">remove-webpack branch</a> on the same repo for an example. I lost JSX support but given that the bundle is 6.8kb compared with the webpack version of 151kb I’m okay with that. It also has the added benefit of working with ES6 modules.</p><h4>Further improvements</h4><p>It would be nice to get ES6 modules support. CommonJS is good enough for now though.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b944e2a4be3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2 things that made our site 10x faster]]></title>
            <link>https://alastairtaft.medium.com/2-things-that-made-my-site-10x-faster-29c2e3a9b151?source=rss-18f61befca76------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c2e3a9b151</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[static-site]]></category>
            <dc:creator><![CDATA[Alastair Taft]]></dc:creator>
            <pubDate>Tue, 27 Dec 2016 11:49:32 GMT</pubDate>
            <atom:updated>2016-12-27T11:58:03.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Our start up’s tag line is ‘Lightning fast web applications’. While our company site was quick, it wasn’t quick enough.</p><p>I spent a day going over these 2 steps to really vamp up the speed of our site.</p><p>While I could take this a lot further and start reducing the bundle and image sizes, I wouldn’t get as good time spent vs improvement ratio, so for now I’ll leave that as a future task. In fact, before we carry on why not go check out our site <a href="https://www.lunait.solutions/">Luna IT Solutions</a> and decide for yourself if it’s quick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hV9lyNzsIrZ3GpRL79cmiQ.jpeg" /></figure><h3>1. Switching to a static site</h3><p>Originally we were rendering each page’s html as a request came in. This seems to be the standard thing to do in 2015/16 but our content is all static, it dawned on me why not just do this ahead of time. Doing it on every request is slow, and needless when the content never changes. In our case the content is served from a CMS system so the initial render will also have to wait for a fetch via an api which also accesses a database. All adding up the time for that initial paint.</p><p>So instead I wrote a few custom build scripts to generate a static version of our site using the current version of the CMS content at build time. This actually solved another problem. It’s a bit undesirable to have the website content change as you live edit in the CMS, by switching it out to this build step we could implement a ‘Publish’ feature where all it had to do was trigger a new build.</p><h3>2. Moved to Firebase</h3><p>Step 1 gave us static assets, which naturally led to step 2… taking advantage of Firebase’s CDN. This basically means our website is served much faster to any user, no matter where they are in the world.</p><p>We were previously using Heroku, but decided to switch to Firebase. Our time to first byte went down from around 600ms (which is super slow) to about 55ms, that’s half a second saved already. This sped our site up so much and also saved a fair bit of money with the free SSL certificate offered. We’re paying $100 yearly (and $20 monthly) for a SSL certificate with a Heroku addon, but there’s no need as Firebase offers one for free.</p><p>It also automatically gzipped our assets, which simplified our build process a bit.</p><h3>Conclusion</h3><p>Static sites served from a CDN are very fast, if you’re content doesn’t change, consider doing the same.</p><p>Also take advantage of <a href="https://github.com/GoogleChrome/lighthouse">Lighthouse</a> it’s an awesome tool for figuring out what’s slow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c2e3a9b151" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>