Posts

,

15 Blogs Every Javascript Developer Should Follow in 2020

I’ve been following the most interesting JavaScript blogs quite for a while now (this is a part of my job running https://weekendjs.com/). There are many of them. More than you might think. There are blogs started more than ten years ago, and there are relatively new ones. Some bloggers are JavaScript superstars, and others are regular engineers like you and me. Some blogs are focused on a particular ecosystem (say Angular or React, or Vue), while others are rather general.

The exciting thing is that the number of good blogs with really robust material keeps growing from one year to another. It is a promising trend, which hopefully will continue.

A few words about who makes it into the list: only the bloggers who write relatively often (at least once per month). Those are all personal blogs, not hubs, companies, etc. And of course, the main metric is the quality of the material.

OK, enough words. Please welcome, in no particular order, the top 15 blogs a JavaScript developer should follow in 2018.

2ality

The author of the “Exploring ES6” book, Dr. Axel Rauschmayer is long known for his deep and comprehensive articles. They are always well-structured and tend to cover the topics in every detail. Usually he writes about ES6/7/8 features and how to use it, but recently, for example, he did a series of articles on ReasonML, which is a hot new JS-transpilable language from Facebook.

David Walsh

David Walsh is an engineer who works at Mozilla from Madison, Wisconsin. David writes regularly (several times per month). His posts are about web development in general. Usually, these are small, understandable pieces for a broad audience on JavaScript’s new features, Node, and more.

Reginald Braithwaite

Reginald “raganwald” Braithwaite, is the author of brilliant “JavaScript Allongé,” one of my favorite JavaScript books. If you haven’t read it, go ahead and do it. Seriously, it’s a pure pleasure, I promise. As you might expect, he writes a lot on functional-related topics. His articles are probably not for beginners and instead aimed at a more experienced audience.

Michael Herman

Michael Herman is a developer and public speaker. He writes about a lot of stuff such as Python, Docker, etc. Technically, I could leave him out of this list. But his write-ups on JavaScript and related material are extremely practical and helpful, so I just can’t leave out his brilliant blog.

Addy Osmani

I’m not sure I need to introduce Addy Osmani. He is a Chrome core developer, a web performance evangelist, and a public speaker. You probably use libraries he has written on a daily basis; just check his GitHub. He also wrote the very popular “Learning JavaScript Design Patterns” book. In his blog though, he writes a lot on Progressive Apps and is one of the core contributors to the concept.

Ponyfoo

This one is easily recognizable by the iconic pixelated image of a unicorn. The author writes lots about new ECMAScript features, in particular modules, and is (as you might expect) in the middle of writing a book about modules.

Dave Ceddia

Dave’s first post dates back to 2015. And it was about Angular 2 (yeah, can you believe it? Time runs so fast). In 2017, though, it seems as if he changed his preferred framework and started writing more on React. He’s also an author of a lovely little book called “Pure React” which is aimed at starters.

Todd Motto

Speaking of Angular, it’s surprisingly difficult to find robust material on the topic. It’s understandable, perhaps, since React seems to be a lot more fun to write about. Well, at least we have this guy. Todd writes a lot on connected topics (TypeScript, NGRX), speaks at the conferences and also does courses. He’s easily the best individual Angular blogger out there.

Tyler McGinnis

Tyler McGinnis is the author of many thorough React courses. So, as you might expect, he also writes a lot about React both Web and Native. His blog also contains a lot of video materials, which are a joy to watch.

John Papa

John Papa is a developer advocate, public speaker, and of course, a blogger. He also authored several courses on for Pluralsight. He used to write a lot on Angular, especially Angular 1, but it seems he’s more into Vue now. If you’re interested in this React alternative you should follow this guy.

Valentino G.

This guy writes a lot of different topics, including Django and Node. Most often he writes about React and friends.

Ben Nadel

I didn’t know about this one until recently, but now it’s easily one of my favorite JavaScript blogs. My favorite part is that he writes a lot about UX and its intersections with JavaScript. Highly recommend it!

Bram Van Damme

It’s interesting that lots of bloggers are from Europe. Like Bram, who is an engineer from Belgium. He writes about JavaScript and also more in general about the web and web development.

Ivan Akulov

Ivan writes about React and Webpack, and also in general about different optimizations you’ll need to do as a web developer. His write-ups are highly practical, and may not suit the beginners.

Robin Wieruch

Robin works in Berlin. He writes a lot (and quite often) about React and friends. But also (and that’s what makes him interesting) he writes about stuff like AI and machine learning. There aren’t a lot of places where you can read articles like “A Web Developer’s Guide to Machine Learning in Javascript” or “Neural Networks in Javascript.” If you’re interested in those topics, you definitely need to follow Robin.

I hope you liked this list. Now go ahead and add them to your preferred RSS reader as I did and enjoy the perpetual flow of the best articles from the JavaScript world!

, ,

Manage Your JavaScript Canvas Elements

The browser JavaScript ecosystem moves fast. It’s easy to become overwhelmed trying to keep up with new browser features and JavaScript application frameworks. Oftentimes, developers get burnt out by trying to keep up, and it can feel like you’re rewriting the same code over and over again.

A good pattern to help avoid this burnout is centralization of concerns. If you’re trying to avoid rewriting the same modules over and over again every time you work with a new framework, you might want to consider writing native JavaScript implementations that don’t rely on your framework and then tying them into the framework with minor modifications, or by treating them as modules using a module loader such as WebPack or Browserify. The most basic option would be to attach them to the global window object directly (if you’re not worried about namespace collisions, at least).

I have hundreds of these singletons to help organize my code. Manually keeping track of instances of various browser APIs can be tiresome, so my preferred pattern is a registry. For this first post, I’ll provide an example of a 2D canvas registry that will create, manipulate, and track instances of canvas elements throughout the lifecycle of an application, allowing you to centralize things like responsive updates and DOM manipulation. For simplicity’s sake, this singleton will be directly attached to the window for now, but in forthcoming posts, I will provide examples on how to package it as an ES6 module for use alongside a framework of your choice. This particular module works well with stock JS applications, React applications, or it can work well as an Angular 1 service with some minor modifications.

First, I’ll explain the structural elements that act as the infrastructure of the module. Then I’ll go through each function, explaining what it does and how it works. Finally, I’ll provide some usage examples to wrap up the post and paste a link to the full module for inclusion in your projects.

Note: this module uses ES6 syntax for clarity. If you prefer ES5 syntax for compatibility reasons, it is a pretty trivial exercise to remove the ES6 specific features.

Module Structure

window.CanvasSingleton = function (){
  let registry = {};

The first line attaches a constructor function (CanvasSingleton) to the global namespace. The second line initializes an empty object that will act as our registry for representing individual instances of our responsive canvas objects.

this.pixelRatio = (function () {
    var ctx = document.createElement('canvas').getContext('2d'),
    dpr = window.devicePixelRatio || 1,
    bsr = ctx.webkitBackingStorePixelRatio ||
      ctx.mozBackingStorePixelRatio ||
      ctx.msBackingStorePixelRatio ||
      ctx.oBackingStorePixelRatio ||
      ctx.backingStorePixelRatio ||
      1;
  return dpr / bsr;
})();

This code is an IIFE (Immediately Invoked Function Expression). This is run as the interpreter instantiates the CanvasSingleton object the first time, as it only needs to be set once per app lifecycle. It sets this.pixelRatio to the measured pixel density of the particular device this code is executing on. By multiplying pixel values by this ratio later–in our render function–and then shrinking the canvas CSS down to the DOM element’s parent dimensions, we can seamlessly support high-DPI displays without having to manually perform this trick for every single canvas on the page. This also makes it easier to use canvas responsively. The long string of references, separated by the || pipe operators, is to help accommodate the various browser-specific implementations of the context.backingStorePixelRatio field.

Lines between the first two and last two are functions attached to the this keyword that will be used for creating, manipulating, and destroying canvases.

The penultimate line of the function returns the this keyword, allowing external code to access any functions or values attached to this.

The Important Bits

The code in the middle of the module is all of the functions we will be using to actually generate and keep track of our various canvas elements. I’m going to go through them one at a time and explain how they work.

  this.create = (parent, render) => {
    let canvas = document.createElement('canvas');
    let [w, h] = [parent.clientWidth, parent.clientHeight];
    let context = canvas.getContext('2d');
    context.identifier = Object.keys(registry).length;
    let listener = window.addEventListener('resize', () => {
      this.update(context.identifier);
    });
    canvas.width = w * this.pixelRatio;
    canvas.height = h * this.pixelRatio;
    canvas.style.height = `${h}px`;
    canvas.style.width = `${w}px`;
    parent.appendChild(canvas);
    context.scale(this.pixelRatio, this.pixelRatio);
    registry[context.identifier] = {
      parent,
      canvas,
      render,
      listener,
      context
    };
    render(canvas, context);
    return context;
  };

The above function takes two parameters. The first needs to be a DOM element, preferably empty. The dimensions of this DOM element will determine the virtual size of the canvas element we’re generating and appending to the DOM.

The Render Function

The second parameter is a render function. This is where you’ll put all of your draw logic. The render function will be passed configured canvas and context objects that can be used to draw. If you want to make your drawings relative to the canvas size, you can use canvas.clientWidth / 100 and canvas.clientHeight / 100 as percentage units.

The render function can be fired manually via this.update, and will also be fired on window.resize events to allow for responsivity. (Note: for more CPU intensive canvas elements, you’ll likely want to debounce calls to the render function to avoid excessive CPU utilization).

The Rest of the Create Module

The first task the create function does is create a canvas element in the document scope. Then, it initializes some local variables, w and h by measuring the client dimensions of the DOM node that was passed into the function as parent. Next, we create a 2D canvas context on the canvas element we created and give it an identifier (an integer that is equal to the number of keys currently in the registry, incremented by one).

The next discrete action this function performs is setting an event listener for the ‘resize’ event. All this does is call the CanvasSingleton.update function and pass in the canvas identifier from the canvas we’re creating.

Next, we set the canvases literal width and height to the measured dimensions multiplied by the devices pixel ratio. The following lines set the canvases style dimensions to the measured dimensions of the parent DOM element. What this means, in effect, is that the canvas is much bigger in memory than it will be rendered, by a factor of the devices pixel ratio. The canvas is compressed by the renderer to the measured size. For devices with pixel ratios higher than 1 (almost everything, nowadays), this means your canvas will be crisp at any pixel density.

The last lines of this function append the canvas element we initialized to the parent element that was passed into the function via parameter, calls the context.scale method with our pixel ratio values to make the high-DPI support work, set the registry entry at context.identifier to be an object containing references to our parent, canvas, render function, listener, and context, call the render function directly once, and then return the context object to the function that called the create function so that code external to this can access the identifier for actions later in the canvases lifecycle.

  this.update = (id) => {
    let {parent, canvas, context, render} = registry[id];
    let [w, h] = [
      parent.clientWidth,
      parent.clientHeight,
    ];
    canvas.width = w * this.pixelRatio;
    canvas.height = h * this.pixelRatio;
    context.scale(this.pixelRatio, this.pixelRatio);
    canvas.style.height = `${h}px`;
    canvas.style.width = `${w}px`;
    context.clearRect(0, 0, canvas.width, canvas.height);
    render(canvas, context);
  };

this.update is a utility function we can call whenever we want to redraw the canvas. It updates the dimensions and scaling of the canvas as well so that our canvases are responsive to new dimensions. It’s also useful to call directly from external code if the data you’re rendering has changed. It takes one parameter: a canvas identifier that is returned as part of the this.create function.

The first two lines initialize some variables. The first set is pulled directly out of the registry. These are just for convenience and clarity. The w and h variables initialized on the second line are measured directly from the original parent element, whose referenced we saved in registry[id].

Next, we redo the setup and scaling work we did on this.create function to ensure that the canvas dimensions continue to match the parent DOM node. Finally, we clear the canvas and then call the render function again.

  this.animateTick = (id) => {
    let {canvas, context, render} = registry[id];
    context.clearRect(0, 0, canvas.width, canvas.height);
    render(canvas, context);
  };

this.animateTick is a function meant to be called inside of a game or animation loop. Ideally, you’d use something like requestAnimationFrame whenever the browser is ready to re-render an animation and change the input state to the render function to make this into a very simple game engine. animateTick is basically a very pared down version of this.update. It too takes a context identifier from this.create.

  this.destroy = (id) => {
    let canvas = registry[id].parent;
    canvas.parent.removeChild(canvas.canvas);
    window.removeEventListener(canvas.listener);
    delete registry[id];
  };

The last function, this.destroy is a general cleanup function. It removes the canvas element from the DOM. Next, it removes the event listener that we set up in this.create for resizing that individual canvas so we dereference the render function and avoid memory leaks. Finally, we delete all of the references in the object at registry[id]. It is very important to call this function when your canvas element is no longer needed; if you spawn a lot of canvases and never destroy them, it can cause memory leaks.

Extremely Basic Usage Example

<!DOCTYPE html>
<html>
  <head>
    <title>CanvasSingletonExample</title>
    <meta charset="utf-8">
    <script src="/canvasSingleton.js"></script> 
    <style type="text/css">
      #parent{
        width: 50%;
        float: left;
        height: 300px;
        margin: 50px auto;
      }
    </style>
  </head>
  <body>
    <div id="parent"></div>
    <script type="text/javascript">
      const canvasSingleton = new CanvasSingleton();
      let canvasReference = canvasSingleton
        .create(document.getElementById('parent'), (canvas, context)=>{
          // set canvas fill to black
          context.fillStyle = '#000';
          // fill context with black rectangle
          context.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight)
          // start path and set the stroke styles
          context.strokeStyle = '#fff';
          context.lineWidth = 2;
          context.lineCap = 'round';
          context.beginPath();
          // start draw cursor at top left, draw a line to bottom right 
          context.moveTo(0, 0);
          context.lineTo(canvas.clientWidth, canvas.clientHeight)
          // stroke line with styles set above.
          context.stroke();
      })
      window.setTimeout(()=>{
        canvasSingleton.destroy(canvasReference.identifier);
      }, 1000*20);
    </script>
  </body>
</html>

This code is an HTML page that contains a width-responsive canvas element. It should have a black background with a small white line drawn diagonally from the top left to bottom right. If you resize the canvas, you can see that it will redraw to match the new dimensions of the parent element. If you are on a high-DPI device, you shouldn’t be able to see any pixelation or excessive aliasing. You can create and manage as many canvases as you want to without writing the responsive or high-DPI boilerplate more than once. You also get a nice handle to destroy the canvas with when you’re done (in the case of the above example, after 20 seconds).

Wrapping Up

I find myself reusing this pattern all the time to wrangle some of the more unwieldy browser APIs into shape. By defining our elements as entries in a registry–outside of the external code that is creating them–and providing utility functions to mutate registry entries, we can negate some of the complexity and separate the boilerplate from the actual code that does the drawing. It’s also easy to debug and inspect this pattern. You can easily trigger draw cycles from a JavaScript console after tweaking values, inspect the contents of the registry, and actually get a feel for how your code is interacting with the render engine itself. I hope that you find the module and moreover the pattern it relies on to be as useful as I have.

One final note: this code is by no means final, nor is it exactly what I use on production systems. I realize there are lots of ways to extend it, enhance it, and refactor it; not least of which is changing the registry to a normal array and using the index as the identifier. This particular implementation of the canvasSingleton concept is focused on clarity over raw performance, for instructional purposes.

, , ,

Official Vue Projects You Probably Don’t Know About

One of the things that Vue has done to set it apart from its competitors, like React, is to create officially supported projects to fill the gaps in its ecosystem. For example, React-Router and Redux were not created by and are not supported directly by Facebook, the creator of React. Instead, they were created by the community and are maintained by the community.

This is not a bad thing, but this means that it could end up no longer being maintained if the maintainer decides to give it up, or it may take a while to make it compatible with new releases of React if there are significant changes. Thankfully, the React Community organization is working to mitigate those issues, but Vue does things differently. Vue-Router and Vuex—the equivalents to React-Router and Redux for Vue—are maintained by the Vue team. The Vue team also works on things like Vue Devtools, vue-loader, and other projects that help integrate Vue development into your normal workflow, rather than leaving that responsibility to the community. Of course, the community is perfectly free to contribute since Vue is open source, so it’s a win-win.

If you’ve spent a non-trivial amount of time looking into Vue, you were probably already aware of the projects I mentioned before, and you may or may not have been aware that they were supported by the official Vue team. In this article, I hope to make you aware of some of the more obscure projects that the Vue team has developed to expand the ecosystem and offer its users officially supported tools that they can trust will be around and up-to-date. Several of these aren’t finished yet, so you’ll have to keep an eye on them and wait it out a bit before they can be truly taken advantage of in production applications. Assuming they ever reach a full release, Vue will eventually be in a better place because of them.

So here’s the list:

#1: Vuex Router Sync

Vuex Router Sync is a tiny library that creates some state in a Vuex store that synchronizes with the Vue Router so route information and changes can be accessed globally from every component in the same way that the rest of the global state is accessed: via a Vuex store. Also when the route information changes, the Vuex store’s reactivity makes it much simpler for components to react to those changes.

Though it isn’t useful for many apps, this is useful for showing the active page in navigation bars and can help in larger applications. It’s also useful if your components need to check the query or parameters for requests.

#2: Vue Component Compiler

Vue Component Compiler isn’t ready yet. In fact, there doesn’t even seem to be any actual code written for it yet. That’s because they’re still discussing how they want it to work and how to design the API, and you can find that discussion in the single open issue the project has on Github.

But what is it? It’s a project for compiling single file components (SFCs) down to JavaScript modules. Of course, they already have something like this, right? Why do we need another SFC compiler? The answer can be found in that issue:

So far, we have seen the logic of compiling an SFC duplicated in multiple projects:

  • vue-loader
  • vueify
  • rollup-plugin-vue
  • jest-vue

…and others. The goal here is to extract shared logic regarding SFC compilation into a dedicated package to avoid redundancy and ensure all of these tools are on the same page regarding SFC features and behavior.

This project personally excited me because the compiler for Jest has always been sub-optimal because it strips out the style section rather than compiling it, and it seems to be a goal for this project to be able to handle compiling styles. Not only will Jest be better supported, but adding features to Vue template syntax or any other part of SFC will be simpler to implement because it will only need to be done in a single project.

#3: Vue Class Component

Many people like the way Angular creates their components using decorators and standard ES2015 class syntax. If you’re one of those people, then you’ll want to take a look at this project because it allows you to write Vue components in a very similar way! Take a look at the example below, and if you like it, you’ll want to take a look at the Vue Class Component project.

<template>
  <div>
    <input v-model="msg">
    <p>prop: {{propMessage}}</p>
    <p>msg: {{msg}}</p>
    <p>helloMsg: {{helloMsg}}</p>
    <p>computed msg: {{computedMsg}}</p>
    <button @click="greet">Greet</button>
  </div>
</template>

<script>
import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  props: {
    propMessage: String
  }
})
export default class App extends Vue {
  // initial data
  msg = 123

  // use prop values for initial data
  helloMsg = 'Hello, ' + this.propMessage

  // lifecycle hook
  mounted () {
    this.greet()
  }

  // computed
  get computedMsg () {
    return 'computed ' + this.msg
  }

  // method
  greet () {
    alert('greeting: ' + this.msg)
  }
}
</script>

#4: Vue Test Utils

Recently we published an article about unit testing Vue components. At the end of the article is a list of a couple tools to help aid your testing of Vue components and one of those, which is currently in beta, is Vue Test Utils. If you’re unit testing your components, and you probably ought to be, then this project could come in quite handy for you.

Vue Test Utils offers shallow rendering, simplified DOM traversal with selectors, simplified event triggering, transition stubbing, and more. Feel free to start using it to help them finish up their beta testing, and then you’ll have a full-featured testing utility belt for your Vue applications.

Conclusion

This is a very exciting time for Vue developers. Vue has really started to prove itself as a contender in the JavaScript framework space and is now beginning to mature into a full ecosystem. Of course, contributors are welcome to help out with any of these projects, so if you can’t wait for some of the pre-release projects to finish up, feel free to help push it along and help out the rest of the community while you’re at it.

, , ,

Simplifying Your Workflow With Vue Development Tools

Simplifying Your Workflow with Vue Development Tools

As you begin to use any framework more, you’ll want some tools that help you streamline your workflow. This is true of Vue as well, so I’ll introduce you to a couple of tools today that will do just that.

Vue-CLI

Vue-CLI is a command line tool that is designed to help you jumpstart your Vue applications by bootstrapping a base application. This is similar to using Angular’s CLI toolYeoman, or other such tools, but it is more like create-react-app in that it doesn’t generate individual parts (e.g. components) for you after the app is bootstrapped; it only sets up the original application for you.

This is sensible because once you have the base application built, pretty much the only thing you make from then on is components. Those are flexible enough to be built in numerous ways and with numerous languages, so it might be better to simply create a shortcut in your editor to create one the way you like it.

Vue-CLI comes with several templates that you can use to build your base application:

  • webpack – A full-featured Webpack + vue-loader setup with hot reload, linting, testing & CSS extraction.
  • webpack-simple – A simple Webpack + vue-loader setup for quick prototyping.
  • browserify – A full-featured Browserify + vueify setup with hot reload, linting & unit testing.
  • browserify-simple – A simple Browserify + vueify setup for quick prototyping.
  • pwa – PWA template for vue-cli based on the webpack template.
  • simple – The simplest possible Vue setup in a single HTML file.

And that’s just the official templates, which do pretty much everything you’ll need without much, if any, customization on your part. If that’s not good enough for you, you can create custom templates, which I won’t get into here. As you can see, though, depending on the template you choose, Vue-CLI not only helps with getting started more quickly, it also installs other tools that help with your productivity long after you’ve begun building the application (e.g. hot reloading with webpack).

To use Vue-CLI, install it via npm (or Yarn if that’s your thing):

npm install -g vue-cli

Then, once it’s installed, you run vue init to build out a new application:

vue init <template-name> <project-name>

Replace <template-name> with the name of one of the templates I listed above, with the username/repo of the GitHub project that houses your custom template, or with the absolute path to a template stored locally on your machine. The <project-name> will become the name of the folder that Vue-CLI creates and stores the new application in.

After that, depending on the template, it’ll ask you a bunch of questions, such as whether or not you’ll use ES Lint or use Karma/Jasmine for testing. That way it can eliminate pieces you won’t use and just give you the things you want and need for your application.

Personally, it took me over a week to build up my webpack configuration the way I wanted it to be. Once I learned about Vue-CLI, it only took a few minutes to get up and running from then on out.

Vue Devtools

So now you have your application built up a little bit, but you need some help debugging it. The Vue devtools have you covered there. It’s a plugin for Chrome devtools, Firefox, or Safari (you’ll need a workaround to get it to work with Safari). It contains 3 tabs that give you a few different ways to look at and debug your applications.

The first tab is a component tree. It looks very similar to the “Elements” tab in the Chrome debugger except instead of showing all the DOM elements, it just shows the Vue components. Also, when you click on one, you’ll see all the current state of all the props, data, and computed properties for that component.

The second tab shows the current state of all the data—including getters—inside your Vuex store. In the left half of this tab’s pane, you’ll see a history of changes to that data. Any time a mutation is called, an entry will be added here. You can “time travel” to temporarily undo changes to the state and see what the app looked like at that point. You can also use the “Revert” buttons to permanently undo mutations or use the “Commit” button to make that snapshot the “base” one. That means you cannot time travel further back than that snapshot.

Finally, we come to the third tab. This is the events tab where you’ll see a list of every time an event was fired from a Vue component. You can click on the event to see the component that fired it, the type of event it was, and its payload.

Each of these tabs has proved their worth to me at least once while debugging or experimenting with my applications. It shows you everything you from the context you are working in most of the time (Vue components and Vuex stores), which is a lot easier than trying to figure it out from the lower-level debugging tools built into the browser. Of course, those browser tools still serve their purpose and you’ll still spend plenty of time using them, but Vue-specific debugging can be made much simpler with the Vue devtools in many instances.

Wrapping Up

These two tools have made my life using Vue much simpler and I’m very grateful for their existence. Hopefully, they can be helpful to you as well.

,

Unit Testing Vue Components

Unit Testing Vue Components

If you’re wise, before you decide to use a framework, you check to make sure you’ll be able to adequately unit test your application if that framework is in place. So, before jumping onto the Vue bandwagon, this question must be answered: can you unit test a Vue application without going through more trouble than it’s worth? Well, let’s take a look at how to test Vue components and you can come to your own conclusion.

Setting Up

There are several unit testing library/framework options, but if you’re looking for a recommendation, then use the Vue CLI to scaffold out your Vue project, using either the “webpack”, “browserify”, or “pwa” template, and then answer “Y” to the “Setup unit tests with Karma + X?” (X is Jasmine when you use the browserify template and Mocha for the other two templates). Then it will pretty much all be set up for you. Many people would prefer to make their own decisions about what frameworks to use and how they set up the project to do testing. That’s not a bad thing, but sometimes it’s better to let someone/something else make that decision for you rather than spending precious developer time on researching your own choice.

In this case, Karma allows you to run all of your tests in multiple browsers at once or just PhantomJS as the default. It also integrates with webpack so you know your components are being compiled the same way they are when the application is built. This is especially useful when using Single File Components (aka .vue files), which can be tricky to compile otherwise. Mocha and Jasmine are both quite popular testing libraries, so you can’t go wrong with either one.

If, however, you really want to consider all of your options, then Jest may be a good solution. It’s touted as being very fast and the snapshots feature can make testing the final HTML output extremely simple. If you’re using .vue files, then you’ll need a pre-processor to compile them. This sadly doesn’t work well with CSS Modules, but there are workarounds that work to an extent.

As another consideration, you may want to have code coverage reporting. In that case Jest is a good option because it’s built in, but Vue CLI will also include code coverage if you decide to do unit testing. In any case, there are several code coverage libraries out there that can integrate with just about any unit testing framework.

Honestly, any framework should work as long as you either use plain JavaScript components or can find a way to compile the .vue files to JavaScript. There are too many options to be able to go into any kind of detail regarding setup, except to say that Vue CLI can do it for you if you’re OK with their choices.

How to Test

For these examples, it’s assumed that you’re using the unit testing setup that Vue CLI scaffolded out for you with the “webpack” template. For the most part, the concepts carry over to the other testing libraries. If you’re using something else, you should hopefully be able to follow along anyway.

To start with, let’s create a relatively simple component that’s pretty useless but will allow us to learn how to test multiple aspects of Vue components. We’ll call it Foo.vue:

 

Now let’s create our first unit test file for this file, which should be located in the test/unit/specs folder if you’re using the same scaffolding template. We’ll call it Foo.spec.js and just write out the very basic things to set up:

import Vue from 'vue'
import Foo from '@/components/Foo' // @ is configured to be our main src directory

decribe('Foo.vue', () => {
  // Our tests will go here 
}

Static Components

The first and simplest thing to test is the static functions on your components. In this case, we can test Foo.data and Foo.methods.giveZero, which should work without instantiating or mounting the component. Foo.computed.msg and Foo.watch.who both reference this, so they’ll need to be tested on an instance of Foo.

it('should have correct `data`', () => {
  expect(typeof Foo.data).to.equal('function')
  const data = Foo.data()
  expect(data.who).to.equal('world')
  expect(data.updates).to.equal(0)
})
it('should return 0 from `giveZero`', () => {
  expect(typeof Foo.methods.giveZero).to.equal('function')
  expect(Foo.methods.giveZero()).to.equal(0)
})

All of these tests should pass, so let’s take a look at testing a component instance since you can’t get very far simply by testing the static component definition.

Component Instances

To do this we need to use Vue to mount the component, but it won’t be mounted to any element in the DOM; it will just render it in memory. There are two ways to do this:

// Mount method 1
const Constructor = Vue.extend(Foo)
const vm1 = new Constructor().$mount()

// Mount method 2
const vm2 = new Vue(Foo).$mount()

While the first method is more verbose, it has the advantage of allowing you to pass in options for props. For example:

const Constructor = Vue.extend(Foo)
const vm1 = new Constructor({
  propsData: {
    someProp: 'custom value'
  }
}).$mount()

That’s equivalent to the following code inside a template:


You’ll likely end up mounting your components quite a bit during your testing, so it may be wise to create a helper function to do it and put it into a module that you can import into all of your tests.

function mount(component, options) {
  const Constructor = Vue.extend(component)
  return new Constructor(options).$mount()
}

Now let’s write a couple tests to see how to use mount:

it('someProp defaults to "default value"', () => {
  const foo = mount(Foo)
  expect(foo.someProp).to.equal('default value')
})

it('someProp can be set', () => {
  const foo = mount(Foo, { propsData: { someProp: 'custom value' } })
  expect(foo.someProp).to.equal('custom value')
})

Note, just like when working inside a component, once an instance is created, all props, data, and computed properties can be accessed directly off the root of the instance. There’s no need to find a computed property under foo.computed.msg or anything like that.

it('computed property is correct', () => {
  const foo = mount(Foo)
  expect(foo.msg).to.equal('Hello world')
})

Component DOM Rendering

Arguably, the most important thing that a component can do is render the correct DOM, so it’s probably important to test if the DOM was rendered correctly. We can access the DOM through the $el built-in property on our component instance. Through this, we can check anything we want, such as whether or not the correct text was rendered in a certain element. For example:

it('render proper DOM', () => {
  const foo = mount(Foo, { propsData: { someProp: 'custom value' } })
  expect(foo.$el.querySelector('h1').textContent).to.equal('Hello world')
  expect(foo.$el.querySelector('p').textContent).to.equal('custom value')
})

Reactivity

One of Vue’s greatest strengths is its ability to automatically propagate changes wherever they need to go when one change is made. For example, a computed property will be updated automatically when one of its dependent properties changes. Also, the component will re-render with new data when a change happens. So we need to be able to test the reactive outcomes of changes we make as well.

When testing computed properties, it’s a simple matter of checking to see if the computed property’s value reflects what it should be once a dependency changes:

it('computed property updates correctly', () => {
  const foo = mount(Foo)
  foo.who = 'universe'
  expect(foo.msg).to.equal('Hello universe')
})

Checking that those updates propagate to the rendered DOM is a bit more trouble, though. If we make a change to foo.who like we just did and then check the DOM, it’ll give us the same DOM output that it had when the foo was initialized, so the following tests will fail:

it('render proper DOM on changes', () => {
  const foo = mount(Foo, { propsData: { someProp: 'custom value' } })
  foo.who = 'universe'
  foo.someProp = 'really custom value'
  expect(foo.$el.querySelector('h1').textContent).to.equal('Hello universe') // FAIL!!
  expect(foo.$el.querySelector('p').textContent).to.equal('really custom value') // FAIL!!
})

This happens because Vue wisely renders asynchronously. This prevents it from blocking the JS thread, but it also allows the entire chain of reactive changes to finish taking place before it renders, so it doesn’t end up rendering multiple times. We can use Vue.nextTick and pass it a callback that will run once it finishes the next rendering cycle, which will allow us to test the DOM.

To allow us to test asynchronous functionality, we need to use a done parameter (you can use any name you want but “done” is pretty common) in the callback to it so we can tell our test runner when the test finishes.

it('render proper DOM on changes', (done) => { // <- Add `done` here
  const foo = mount(Foo, { propsData: { someProp: 'custom value' } })
  foo.who = 'universe'
  foo.someProp = 'really custom value'

  Vue.nextTick( () => {
    expect(foo.$el.querySelector('h1').textContent).to.equal('Hello universe')
    expect(foo.$el.querySelector('p').textContent).to.equal('really custom value')
    done() // Call `done` to say we're done
  })
})

Alternatively, you can return a Promise if your test runner supports it (I believe all latest releases of test runners do). And if you’re using Promises, you make it easier to read by using async functions with async and await. First, we’ll need to convert nextTick to use promises though by creating a helper function:

function nextVueTick() {
  return new Promise((res) => Vue.nextTick(res))
}

Now we can convert our previous test to look like this:

it('render proper DOM on changes', async () => { // <- remove `done` and add `async`
  const foo = mount(Foo, { propsData: { someProp: 'custom value' } })
  foo.who = 'universe'
  foo.someProp = 'really custom value'

  await nextVueTick() // <- use `await` instead of a callback

  expect(foo.$el.querySelector('h1').textContent).to.equal('Hello universe')
  expect(foo.$el.querySelector('p').textContent).to.equal('really custom value')
})

If you're using Jest or another testing framework that supports snapshots, the simplest way to test the DOM is simply to use foo.$el.outerHTML and compare it to a snapshot. That ensures you're able to test the entire rendered DOM rather than picking and choosing bits to check.

Spying on Functions

We can also use spies to make sure that certain functions are called:

it('call `giveZero` on click', () => {
  sinon.spy(Foo.methods, 'giveZero') // <- spy on `giveZero`
  const foo = mount(Foo, { propsData: { someProp: 'custom value' } })
  
  foo.$el.dispatchEvent(new Event('click')) // trigger event that will call giveZero
  
  expect(Foo.methods.giveZero.called).to.equal(true)
  Foo.methods.giveZero.restore() // Remove the spy
})

Note that we create the spy on the component definition rather than on the instance in this case. This is because when the instance is created, the click handler will have a reference to the method that was already defined. If we override it with a spy on the instance, it will never be called because the spy won't get registered as the click handler. Also, note that we're checking Foo.methods.giveZero.called rather than foo.giveZero.called. This is because when an instance is created, Vue will wrap giveZero, so foo.giveZero.called is undefined. Calling Foo.methods.giveZero.restore() will return giveZero to its original function and will prevent other tests from using the spy.

We can also use spies to check on watch functions, which are similar to DOM rendering in that they are asynchronous (there are ways to make them synchronous, but generally you won't be doing that). This means we'll need to bring back our nextVueTick helper:

it('watcher triggered when `who` changes', async () => {
  sinon.spy(Foo.watch, 'who') // <- spy on `who` watcher
  const foo = mount(Foo)

  foo.who = 'universe'
  await nextVueTick()

  expect(Foo.watch.who.called).to.equal(true)
  expect(foo.updates).to.equal(1)
  Foo.watch.who.restore() // Remove the spy
})

Conclusion

That's pretty much it. As you can see, just about everything about Vue components is testable without requiring too much finagling, so Vue's testability should not prevent anyone from making it their choice of web UI framework.

Additional Help

If that's not simple enough for you, then maybe you should check out one of the following libraries that are designed to simplify some of the aspects around testing Vue components.

Avoriaz: This library simplifies mounting, along with being able to pass more options in during mounting. It wraps components to help make DOM traversal and event triggering simpler. Avoriaz can also do shallow rendering so the rendered DOM isn't dependent on child components. With this in place, you won't need to update tests for parent components when the child component is changed. Finally, it offers a method to synchronously re-render, but asynchronous watchers still need to use Vue.nextTick.

vue-test-utils: This library is officially supported by the Vue development team, but currently it's only in beta. It took heavy inspiration from Avoriaz, but is looking to expand its capabilities as well as make improvements to the API.

, , , , ,

Basics to Reading/Writing Cookies with JavaScript

Cookies are relatively small text files that a web browser embeds on a user’s computer. Cookies allow otherwise stateless HTTP communications to emulate state (i.e., memory). Cookies are being replaced by somewhat newer technologies such as local storage and session storage; however, cookies are still widely used by many major websites today. For that reason alone, it’s a good idea for you to familiarize yourself with how cookies work. Additionally, it’s fun to see how you yourself can use JavaScript to read from and write to the your browser’s cookie API. In the following tutorial I’ll show you how to do precisely that. Let’s get cookie-ing!

First, let’s look at how to use JavaScript to read cookies: To achieve this, simply write document.cookie in your JS file or in your browser’s JS console. You can output the value to HTML or just simply log in the console. Here’s an example of what you might see if writing cookie data to HTML (Note: Your browser needs to have cookies enabled and values present for the demonstration to work):

See the Pen rjMjgp by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Yeesh.. what a mess! No worries, we can do some formatting. You’ll notice that there are = and ; interspersed throughout the cookie text. The = denotes key=value pairs while the ; delimits the individual pairs. So in order to clean things up a bit, you might write something like this:

See the Pen zNKZOj by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Much better!

Now, how to write cookies: To write cookies using JavaScript, simply use the same document.cookie property we looked at before, but this time set it equal to a key=value pair (as a string) using the assignment (=) operator. Like this:

See the Pen LxRWKV by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

See it? In green? I just added my email address as a cookie to your machine. Feel free to drop me a line! :) Of course you can delete it if you want…

Moving on, let’s say you want the value of just 1 key=value pair within the cookie. What to do..? Well, you could write a custom function to do something like this:

See the Pen zNKZdm by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

And from there, you can do all kinds of things depending on whether or not a certain key=value pair exists as a cookie on a user’s machine. One of the most common uses for cookies is keeping users logged in to a credentialed website (such as Facebook, Twitter, of YouTube) by placing a cookie on the user’s machine once successfully logged in. The logic goes something like:

    if (key=value exists) → show logged in content, if (key=value doesn’t exist) → prompt user to log in

that kind of thing.

And there you have it, a basic introduction to accessing and manipulating cookies using JavaScript. For more detailed information on cookies, you can always check out sites like MDN.

Thanks for reading!

, , , ,

230 Curated Resources and Tools for Building Apps with React.js

This post will curate the best resources, tools, libraries, and articles that will help you learn to build production applications with React.js. This 6000 word post will take you from getting started with React, through UI design, routing, testing, deployment, and continuous integration. There are many sections and you should feel free to jump to the resources you need.
Getting Started
+ Demos and Apps
+ Tutorials and Articles
+ Video Tutorials and Courses
+ Community
+ Boilerplates
+ UI Components
+ UI Libraries and Frameworks
+ Routing
+ State Management
+ Other Useful Libraries
Development Tools
+ Text Editors
+ Build Tools
Testing
+ Articles
+ Utilities
+ Automated Backend Testing Services
Performance
+ Articles
+ Tools
+ Libraries
Deployment
+ Continuous Integration Articles
+ Continuous Integration and Deployment Software
+ Cloud Server Provider
+ Continuous Integration in React Apps
Resources for Further Learning
+ Articles and Tutorials
+ Courses
+ Books
+ Talks and Conferences
+ More React Resources

Explore appendTo’s React Courses

Getting Started

First off, let’s start at the very beginning. This section assumes you have zero-knowledge on React and have at least a solid foundation on JavaScript basics.

Demos and Apps

You already know that you want to learn React (that’s why you’re here right?). But a good first step when learning about a new technology is to know what’s possible with it. And the best way to go about that is to check out demos and existing apps that have been built with it.

Demo Apps

Production Apps

Tutorials and Articles

Now that you know what’s possible with React, it’s now time to take a look at how you can get started learning it.

If you’re the type of person who wants to have a general idea on how a specific technology works, then ReactJS for Stupid People is a good place to start. It talks about what React is, what you can do with it, its limitations, and whether you should use it for your future projects or not.

If you’re like most people, you either came from a jQuery or Angular background before you came to know about React. Tutorials which uses a well-known library as a point of reference in learning something new is a good way to understand how things are done in that new technology. Being able to translate what you’re used to doing in an older technology to and apply it to a new one can be very empowering to new developers who are just trying the waters.

Now that you have an idea on how React works, it’s now time to dive into the core React concepts. Taking the time to understand the core concepts first before trying to write even a single line of code can really go a long way when learning React, and in fact (news flash coming up) any other new technology that you’re trying to learn. This will make the code that you see in React tutorials “click” faster. It also ensures that you won’t just end up copy-pasting the code from these tutorials. Having a good understanding of the core concepts enables you to distinguish how a specific thing works when you see them in action. So without further delay, here are a few tutorials you can read in order to understand the core concepts behind React:

Video Tutorials and Courses

Free Courses

  • Egghead.io: React Fundamentals – this series will explore the basic fundamentals of React to get you started.
  • Mindspace: ReactJS Basics – teaches the basic concepts of React.
  • Learn ReactJS – if you want a more hands-on React course, this one is for you. Aside from the usual “getting to know the syntax” part, they also have projects and quizzes to make sure you really understand what you learned.
  • ReactJS Program: React.js Fundamentals – uses a combination of tutorials, video tutorials and a project that you will build throughout the whole course.

Paid Courses

If you have some cash to spare, consider enrolling on the following courses:

  • Powering Up with React – a combination of video tutorials and hands-on exercises to get your hands dirty in using React.
  • React for Beginners – a course by Wes Bos, a Full Stack Developer, Speaker and Teacher from Canada. The course is a bit pricey but it will be worth it, because this course covers all there is to know about the fundamentals of React.js. Each video tutorial is really concise, very engaging and most important of all, it’s not sleep-inducing.
  • React.js: Getting Started – learn the basics of React.js, and build an in-browser, math skills kids’ game from scratch with it.

Community

Now that you’ve begun your journey in writing React code, and maybe have followed through a tutorial or two.

In your journey in learning React, there will always be a time wherein you get stuck with a specific bug or error in your code. Often times simply searching for that specific error on Google would help. But what if there’s no error at all? Or Google doesn’t really return useful results. In those cases what you need is a community. Most of us already know Stackoverflow. Most of the search results that you see on Google when you search for a specific error are almost always from Stackoverflow. But aside from Stackoverflow there are other good places where you can get help and talk about React stuff in general.

Now that you have an idea how React works, its core concepts and how to build things with it, its now time to take things further by learning about the tools which you can use while developing apps with React.

Boilerplates

A boilerplate is a useful tool for quickly getting started with a React project. As you might have already found out using the resources given above, the React code (JSX) that you write can’t actually be executed by the browser. This means that it has to go through a compilation process before the browser can understand it. The compiler accepts your JSX code and spits out the plain JavaScript code that’s readable by the browser. This is where boilerplates comes in. One of the tools which comes with a boilerplate is the build tool, which is responsible for compiling your JSX code.

To put it simply, boilerplates comes with a collection of tools and libraries that are commonly needed in developing React apps. Examples of such tools are build tools, test runners, and libraries for routing and state management.

  • Create React App – if you want to quickly get started writing React apps without worrying too much about the build/compile process, this is the way to go. In my own opinion, this is the only beginner-friendly boilerplate among this list.
  • React Starter Kit – if you’re looking for a boilerplate that allows you to easily set up not just the front-end but the back-end as well, this boilerplate is for you. It is built on top of Node.js, Express, GraphQL, React.js, Babel 6, PostCSS, Webpack, and Browsersync.
  • React Boilerplate – a production-ready boilerplate for starting out React projects. Highly focused on performance and best practices.
  • React-Redux Starter Kit – if you want a boilerplate which has minimal features and isn’t too opinionated about how to do certain things (project structure, build configuration) then this one is for you.

Those are just a few of the boilerplates that allows you to get started with your React projects quickly. Note that it’s not a requirement to use these boilerplates. Sooner or later you’ll find out that they’re either too rigid or too hard to customize. This is because some boilerplates can be too opinionated about how to go about things. Once you’ve tried using one or two boilerplates, you’ll pretty much have an idea on how to build your own. Every project is different so building your own boilerplate makes sense, since you only include things as you need them. This also adds up to your productivity later on, as you no know exactly where to look when you need to customize things.

UI Components

The main idea for using React is to be able to create UI components that can be reused anywhere in your app. Since React is a pretty popular library, developers and designers around the world have already created a lot of useful components that can be used in most projects. This means that you don’t need to write everything from scratch. Most of the components that you might need in your project might have already been written before.

In this section, let’s look at some useful components which you can use in your projects.

Those are just some of the components which you can use on most projects. If you need to find a custom component, you can check out the following component curators:

If you’ve looked through the curators above, you’ll notice that each component either points out to one of these two sites:

  • Github – hosts the source code for the components.
  • NPM – package manager that enables developers to install the components locally.

This means that you can actually directly search on Github or NPM for your React components and libraries.

UI Libraries and Frameworks

If you want your apps to have a standard look and feel, a good place to start is by picking a UI library or framework. Libraries and frameworks comes with a set of components with the same theme. Each of them comes with a different set of components and a different way of doing things, so you have to choose which one fits your needs and your values.

  • Material-UI – React components that implements Google’s Material Design.
  • Ant Design – a collection of components that follows Ant Design, a design language for creating user friendly and beautiful websites.
  • React Bootstrap – the Bootstrap framework re-implemented using React.
  • Rebass – a collection of 57 Configurable React Stateless Functional UI Components.
  • React Toolbox – similar to Material-UI in that it also implements Google’s Material Design. The only difference is that it uses css modules intead of inline styles.
  • Elemental UI – a UI Toolkit for React.js Websites and Apps. If you’ve used Bootstrap before, the look and feel of their UI is similar to Bootstrap’s.
  • Grommet – an accessibility-focused framework for creating amazing user experience.
  • Belle – Configurable React Components with great UX.
  • Cx – a modern framework for building visually appealing, data-oriented, web applications.
  • Reusable Components by Khan Academy – useful components from Khan Academy.
  • VistarMedia Components – a collection of React components from VistarMedia. The components has the same look as Bootstrap.
  • React Topcoat UI – if you’ve used the Topcoat CSS framework before and you want the same look and feel for your React app.

Explore appendTo’s React Courses

Routing

Routing is an important part of every application. It keeps the UI in sync with the current URL that is being accessed by the user. For example, when http;//myapp.com/#user/1 is accessed, the UI will automatically update to show the page being asked.

Here are some of the routing libraries that you can use with React:

  • React Router – the De facto routing library for React. In the beginning, this is what you want to use as it includes all the bells and whistles that you need to start experimenting with routing.

Once you’re acquainted with React Router, you might notice that there are some features that you don’t really need, or you don’t really like the way it does things. Here are a few alternatives that you might want to check out:

  • React Mini Router – if you don’t want your routing solution to consume that much space, you can use this library instead. It has a few external dependencies and only becomes 4kb when gzipped.
  • React Router Component – a declarative router component for React.
  • Universal Router – A simple middleware-style router that can be used in both client-side (e.g. React, Vue.js) and server-side applications

  • router5 – a framework agnostic routing solution.

State Management

Another important part of any application is how you manage the state. At this point, we already know that each component can have their own state. This works for really small applications because you can just pass the state from one component to another by means of props. But for real-world apps, you need a way to make the state accessible throughout the whole app. Especially the one’s that are “global” by nature (e.g. settings). This is where state management comes in. React doesn’t come with this kind of functionality, but thankfully there are libraries that allows you to manage global app state in a sane manner.

Redux is one such library. Redux allows you to have a global state for your app so that the different components in your app can communicate with each other. Note that Redux isn’t specific to React, so you have to install React Redux as well so that you can easily work with Redux within the React environment. After learning plain React, Redux is the second step. Here are some resources that will help you learn it:

Free Resources

  • A Cartoon Guide to Redux – this is a great read if you want to know about the different components that make up Redux and how they work together. The visual can really help you in understanding the different concepts better.
  • Learn Redux – from the same guy who created the React for Beginners course. This course will teach you how to create an Instagram clone using React.js, Redux and React Router.
  • Getting Started with Redux – a course from the creator of Redux himself, Dan Abramov. If you’re looking into learning the nitty gritty details of using Redux, this is the course for you. Because it will not only teach how to use Redux within a React app, it will also dive into the details of using the different tools available in Redux.
  • Building React Applications with Idiomatic Redux – in this course you will learn about the production-ready techniques for building React and Redux applications.

Paid Courses

  • Modern React with Redux – learn the basics of React, Redux as well custom components such as Google Maps and charts by developing an app.
  • Advanced React and Redux – learn how to implement authentication, test components and use middlewares.
  • Building Applications with React and Redux in ES6 – an all in one course that shows you how to setup your environment for React development, teach you the basics of React and Redux, and how to test React components and your Redux code.

Redux is pretty much the De facto standard library for managing state in React apps. But that doesn’t mean that you can’t choose to use other solutions.

Other Useful Libraries

Here are other React libraries that you may find useful:

  • React Icons – use popular icon sets (e.g. Fontawesome, Octicons) in React.
  • React i13n – allows you to include instrumentation (analytics) to your app.
  • Omniscient – provides abstraction for React components that allows for fast top-down rendering. This uses immutable.js for immutable data.
  • Search Kit – a collection of UI components for creating beautiful search applications using ElasticSearch.
  • React Motion – an animation library.
  • React Forms – provides a set of tools for React to handle form rendering and validation.
  • react-intl – provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations.

Development Tools

As you’re using React, Redux and other libraries you’ll notice that there are things that you need to do repeatedly. Namely writing out common React functions and debugging your code if something goes wrong. In this section we’ll look at some of the tools that you can use to ease up your React development.

Text Editor

Once you’ve gotten used to the React syntax, it’s high time you install plugins that will help you to easily write React specific code. Two of the most popular one’s are Atom and Sublime Text, so we’re going to look at specifically these two. You can start the tooling journey by reading one of the articles below:

Build Tools

Once you’re happy with your text-editor setup, you need to get acquainted with a build tool. If you’ve checked out the Boilerplates section earlier, you might have already introduced yourself to one such build tool: Webpack. Build tools play a role in the development, testing and deployment phase of your application. Here are a few points just to give you an idea on what build tools does:

  • They accept your JSX and ES6 code and spits out JavaScript that’s readable by the browser.
  • They compile all your modules together into a single file that can be linked into your page.
  • They listen to source code changes and use either live reloading or hot module replacement to update the preview of your app in the browser.
  • They run your tests.

Now you know that there’s no escaping build tools when it comes to React development. Of course, in the beginning you can use Create React App and it will handle the compilation of your React code for you. But as soon as you get out of the “beginner zone”, the next thing that you need to learn is how to use a proper build tool. Here are some resources that can help you with that:

Note that Webpack isn’t the only build tool out there. There are lots of other tools that you might want to check out. Webpack is pretty much the De Facto standard when it comes to React apps, that’s why it’s the one that I introduced.

Debugging

Next you need to up your debugging game. That means no more using console.log when you’re trying to find out the cause of an issue.

  • React Dev Tools – allows you to inspect a React Renderer, including the Component hierarchy, props, state, and more. This tool is currently available on Chrome and Firefox.
  • React Inspector – allows you to inspect data in your React apps ala Chrome Dev Tools.
  • Redux DevTools – allows you to inspect state and action payload as they happen. Actions can also be cancelled so you can see the previous state before the action was fired.
  • Reactotron – an OS X app for inspecting your React JS and React Native apps.

Once you’re productive in using your newly found tools. You can start looking for other tools that can help you in developing React apps. Here are a few that you might want to start with:

  • React Storybook – a UI development environment for your React components. It allows you to visualize different states of your UI components and develop them interactively.
  • React Styleguidist – a style guide generator for your React components.

If you want more, Facebook has compiled a list of tools that you can use while developing in React:

Testing

In order to ensure that your code works as expected, you also need to perform tests. Three of the most common one’s are unit tests, functional tests and integration tests. If you’re not aware of any of these, I recommend you to read this article by Eric Elliot on JavaScript Testing: Unit vs Functional vs Integration Tests. That article will teach you everything you need to know about those three types of tests, why they are important, and it will also show some sample codes for each type. Testing also plays a huge role in Continuous Delivery, which is tackled in the Deployment section. Which is why testing plays a very important in the deployment of quality software.

Below are some resources that you can use to get started with your testing adventure. Note that a few of these are for testing JavaScript code in general, not just testing your React code. This is because testing should be holistic. The entirety of the app needs to be tested, so that you get the full benefit.

Testing Articles

  • Writing Testable JavaScript – shows you organize and write your code so that it can be easily tested. This uses Mocha as the test framework, Chai as the assertion library, and jQuery to verify the contents of the page. There’s also a similarly named article which is a good read as well.
  • A Gentle Introduction to JavaScript Test Driven Development – the first part of a three-part series that teaches you how to get started with TDD in JavaScript. In this tutorial, you will be building a simple application which in which you apply TDD. This means that not only do you get to see how to test code, you also get to see the decisions behind why a specific code is written in that specific way.
  • Unit Testing and TDD in Node.js – shows you how to get started in unit testing your Node.js code using Mocha, Chai and Sinon.

Once you have a good feel on how to do unit testing in JavaScript, the next step is to actually apply in your React apps:

Testing Utilities

These are the testing tools that are mentioned in the articles above:

  • Jest – a test runner.
  • Enzyme – a testing utility for React.
  • Mocha – a test framework for JavaScript projects.
  • Nightwatch.js – a functional testing tool. It verifies that the functionality of your app work correctly based on the user’s point of view.

Automated Backend Testing Services

You can use any of these two services for manual and automated cross-browser Selenium testing:

Performance

Now that you’re sure your components really do what you intend them to do. It’s now time to start looking at how to improve the performance of your React apps. Note that in most cases you don’t really need to check the performance of your app. Especially if it’s just a fairly standard app. However, if you have very complicated views you may start looking into your app’s performance. Here are a few signs that your app needs to have a performance evaluation:

  • It needs to work with lots of data.
  • Multiple parts of the app is updated at the same time.
  • It has lots of user interactions which updates the views.

Performance Articles

The following articles will give you an idea on how to get started in performance debugging your React app:

Performance Tools

Here are the tools that you could use for debugging the performance of your React apps:

  • ReactPerfTool – used for debugging the performance of your React application in a visual way.
  • React Render Visualizer – a visual way to see what is rendering and why. Each component is highlighted when they are mounted or when they are updated.
  • Why did you update? – a function that monkey patches React and notifies you in the console when potentially unnecessary re-renders occur.

Explore appendTo’s React Courses

Performance Libraries

There are also some libraries that you can use for optimizing performance:

  • React Static Container – renders static content efficiently by allowing React to short-circuit the reconciliation process.
  • React Fast Click – automatically adds fastclick touch events to elements with onClick attributes (and those that require special functionality, such as inputs) to prevent the delay that occurs on some touch devices.
  • react-lazyload – used for lazyloading components, images, and other parts of your React application.
  • React Infinite – used for optimizing the performance of infinite lists.
  • react virtualized – a collection of React components for efficiently rendering large lists and tabular data.
  • Inferno – an extremely fast, React-like JavaScript library for building modern user interfaces.

Deployment

Finally we get to deployment. This is where you set up continuous integration and deployment. If you’re new to these concepts, continuous integration is a development practice where developers frequently push code into a shared repository (e.g. Git, Mercurial). All the codes are then automatically tested (e.g. unit tests, integration tests) on a staging server. If there are errors and other problems with the code, they’re immediately reported to the developers. All of this is orchestrated by a continuous integration software such as Jenkins. Once the errors are made known to the developers, they can immediately fix the issue and push the updated code. Once all the tests passes, the current build is automatically pushed to the production server.

Continuous Integration Articles

If you’re new to continuous integration, have a read at the following articles:

Continuous Integration and Deployment Software

Now that you know all about the steps involved in continuous integration, it’s now time to pick a continuous integration service. What you pick should be based on the needs of your specific project. For example, if you use pull requests in Github to keep track of a specific change and review the code. You should pick a CI service that can do that.

Here are a few continuous integration services that you can use:

If you want to host your own, you can use the following open-source CI servers:

Cloud Server Provider

React apps are just your ordinary web apps so you can use your existing cloud server provider for deploying:

Continuous Integration in React Apps

After you’ve learned the basics of Continuous Integration, decided which CI service, and picked a cloud server provider to use. The next step is to apply what you’ve learned and actually deploy your React application.

Since day 1 we all know that React doesn’t exist alone. There are other components that may be used in your code. That also includes your back-end code, which is most commonly Node.js. But others might also be using PHP, Ruby, Python or any other server-side language. This means that you should include those in your tests as well.

As you have already learned, the most important part of continuous integration is the testing process. First you test your code locally, and if it passes, you push it to the staging server for another set of tests. If it fails, you go back to step 1 until such time that all the tests passes. Once all the tests passes, only then is the code pushed to production.

But how specifically can we set this up for React applications? Well, by now you should already be proficient in using Webpack, Browserify, or any other module bundler that you decided to use. So it’s only a matter of figuring out how to automatically run tests when you push changes to your staging server, have the CI server generate a report on the results of the test, and automatically push the code to the production server when all the tests passes.

A huge part of your deployment process is handled by the build and testing tools of your choice. As you’ve learned earlier, Webpack is the one that’s most commonly used in React apps. So it is used together with the testing tools to ensure that the app has no errors. If you’ve skipped the Development Tools part, now is a good time to read through that.

Here are a few resources that can help you in filling the blanks. Note that most of these talks about the back-end since there are only a few apps that are purely client-side:

Resources for Further Learning

Now that you’ve learned all of the process involved in developing apps with React, you can now sleep peacefully at night. Or not, because just like everything in life, you never actually stop learning. There’s always something new to learn. This is more true in a field like web development because there’s always something new to look forward to everyday. New frameworks, new libraries, new best practices.

So in this section I’ll provide some resources to get you started in learning some more React stuff.

Articles and Tutorials

Those are just a handful of articles that you ought to read if you want to level up your React skills. And because the web industry constantly moves forward, you can expect things to change in a month or two. Meaning the articles that I’ve linked above might become outdated. So the best way to keep yourself updated is to occassionally check out blogs about React. Medium is a good place to start, because it is where developers gather to share their experiences in building apps with React:

Courses

Explore appendTo’s React Courses

Books

Free

Paid

If you want more, the author of the React book that I mentioned earlier has also compiled a list of books on React:

Talks and Conferences

The React website also compiles videos from the community:

If you want more, there are React conferences around the world which uploads their talks on Youtube:

Again, the React website compiles a list of conferences about React. So if you’re looking into attending a React conference, you can check out this page occassionally:

Videos from previous conferences are also linked in there if they’re available. So even if you can’t personally attend, you can still learn something.

More React Resources

If you’re still hungry for more, check out the following awesome lists on Github:

Conclusion

In this post, you learned all about the things involved in creating a React app. Hopefully this post has helped you in your journey to become a full-fledged React developer.

, ,

A Simple Primer in JavaScript Recursion

Recursion is a concept that is not unique to JavaScript. It is used in all programming languages. Though it is an important part of Javascript that sometimes gets muddled or overtly complex. Recursion is simply when a function calls itself.

A function that calls itself is comparable to a loop. Both of these methods are executing their code multiple times. They also both require a condition to stop an infinite loop or infinite recursion. A simple example of recursion is seen through factoring.

Factorial Recursion

The mathematical concept of a factorial is a perfect case to use recursion. A factorial is represented by (n!). For example, n! = 1×2×3×4×..×n is the main formula. The following examples show the start of a factorial table.

1! = 1
2! = 1×2 = 2
3! = 1×2×3 = 6
4! = 1×2×3×4 = 24
5! = 1×2×3×4×5 = 120
6! = 1×2×3×4×5×6 = 720

The underlying concept of recursion is doing the same thing over and over again. Factorials demonstrate this and can be programmed into a recursive function. The following code is an example of this.

function factorial( n ) {
if ( n === 1 ) {
return 1;
}
return n * factorial( n - 1 );
}

This code fits the correct parameters for recursion. The function is calling upon itself and it has a condition — return, to stop itself from entering into an infinite recursion. This is the simplest demonstration of the concept.

Loop to Recursion

Another great example of recursion can be seen from converting a loop. Take, for example, this simple countdown while loop.

var countdown = 5;
while(countdown > 0) {
console.log(countdown--);
}

When this loop executes, countdown’s value changes with each print out of the subsequent number. This same while loop can be written using a recursive function.

var counter = function(amount) {
if (amount > 0) {
console.log(amount);
return counter(amount - 1);
} else {
return amount;
}
};
counter(5);

The counter is called upon inside the definition of counter function. Each time counter is executed the engine tracks where it’s being called from. The major difference is that this function hasn’t modified the state of the internal variables inside the function. It executes them one after the other. It doesn’t store them and let them stack up on one another.

Tail Call Optimisation

When a function calls itself recursively in Javascript it creates a new stack. A stack is a block of memory that keeps track of the function’s information. Creating a stack causes the JavaScript engine to work much harder and drain memory. This can cause an error if not coded correctly. Herein lies the next example.

function factorial(n, register) {
if (n === 1) {
return register
}
return factorial(n — 1, n * register)
}
factorial(6, 1) // == 720

A tail call function returns the value from the original return value. The last return factorial(n — 1, n * register) line is the tail call. This is a standard way to prevent a recursion from stacking onto themselves repeatedly and draining away all the memory. Recursive functions in JavaScript need to track where they’ve been called every time.

Tail call optimization has become standard in ES6 and they makes sure that each recursion cycle is called one after the other. This avoids stacked up memory. Tail call optimization is considered one of the more difficult methods to learn about. But it is an essential tool in creating or deconstructing a recursion function.

Overall, all of these examples can help guide a developer’s understanding of recursion functions. They are helpful for factoring, looping more efficiently and executing anything repetitive that calls upon itself.

,

Avoiding Memory Leaks in JavaScript

Memory management

Efficient memory management is a crucial part of any coding practice. When memory management is poor, memory leaks are created which slows down performance and causes crashes. A memory leak occurs when a section of memory that is no longer being used is still being occupied needlessly instead of being returned to the OS. Different programming languages tackle the task of memory management using different methods. In some languages like C and C++, the programmer manually allocates memory when needed, and then frees up the memory after it is done being used by the program. JavaScript uses an automated management method called garbage collection. The garbage collector periodically checks for “garbage” or memory that is no longer being referenced by any objects in the program. It then frees up this memory to be used. There are some languages that use a combination of both methods to avoid memory leaks.

Causes of memory leaks

Though the garbage collection method is highly effective, it is still possible for memory leaks to occur in JavaScript. Being aware of the reasons memory leaks occur, allows a developer to come up with preventative measures. Listed below are a few of the various reasons a memory leak can occur.

Browser Bugs and Extensions– A well-known reason memory leaks occur is due to browser bugs and problematic extensions. For example, when the Filterset.G updater in Firefox is used with FlashGot, it creates a memory leak. In these cases, uninstalling or updating the extension solves the problem. Previous versions of Internet Explorer such as IE6 used to create memory leaks because they couldn’t handle circular references between DOM objects and JavaScript objects. That was fixed with the release of IE8.  

Event listeners– Failure to remove event listeners can cause memory leaks. While this is not always the case, it can be if the DOM element and its corresponding event listener don’t have the same lifetime. Also important to keep in mind is that if you have a tree of objects, the listeners of the children need to be removed along with the listeners of the objects themselves.

Caches– Be wary of data structures that store large amounts of data. Putting objects in large tables, arrays and linked lists can cause memory leaks. To prevent this always specify an upper bound for large data structures.  

Tools to avoid memory leaks in JavaScript

There are numerous methods and techniques to tackle the problem of memory leaks. Below is a brief overview of a few tools in the browser that can be used to debug or avoid memory leaks. More information about memory management browser tools can be found for Google Chrome and Mozilla at the linked sources.

Task Manager– The Google Chrome task manager monitors a page’s memory usage in real time. It gives you information about activity in native memory and the JS heap. Under the Memory column you will find if DOM nodes are being stored in memory. Under the JavaScript memory column, you will find information about how much memory is being used by reachable objects.    

Timeline– If you want to know how much memory your page is using over a period of time, use the timeline panel. The timeline allows you to make recordings. A forced garbage collection can be recorded and examined to detect problems.

Snapshot– Heap snapshots provide information about memory distribution of the JS objects and DOM nodes at a specific point in time. Snapshots can be examined to detect detached DOM nodes.

about:memory– The simplest way to monitor Firefox’s memory usage is using the about:memory page. You can generate and interpret memory reports to debug your applications. The memory reports are divided into sections and subsections which allow for a thorough and organized analysis of memory usage.

Valgrind Valgrind provides high quality tools to debug memory management problems including leaks. It comes with a heap profiler, memory error detector, thread error detectors and more. Valgrind can also be used to build your own analysis tools.

Conclusion

Though JavaScript’s garbage collected method does a good job of memory management, leaks can still occur. It is good practice to be aware of the causes of memory leaks and take steps to avoid them. Various tools exist to help with memory leak prevention. Not all memory leaks are noticeable immediately and are found only after some time has passed. It is easier and less time consuming to be proactive in avoiding leaks than finding solutions when a memory leak has already occurred.  

, , ,

Functions as First-Class Objects in JavaScript: Why Does This Matter?

Functions in JavaScript are first-class objects (or “first-class citizens”). Fascinating, but… what does that mean? Why does it matter? Read on and we’ll have a look!

We’ll start with the basics: What does first-class citizenship mean in general? First-class citizenship, within the world of programming, means that a given entity (such as a function) supports all the operational properties inherent to other entities; properties such as being able to be assigned to a variable, passed around as a function argument, returned from a function, etc. Basically, first-class citizenship simply means “being able to do what everyone else can do.”

In JavaScript, functions are objects (hence the designation of first-class object). They inherit from the Object prototype and they can be assigned key: value pairs. These pairs are referred to as properties and can themselves be functions (i.e., methods). And as mentioned, function objects can be assigned to variables, they can be passed around as arguments; they can even be assigned as the return values of other functions. Demonstrably, functions in JavaScript are first-class objects.

Let’s look at some examples/tests:

Can we assign a function to a variable?

See the Pen JRVgLw by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Yes we can!

Can we pass a function as an argument to another function?

See the Pen XjQvqY by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Sure enough!

But can we return a function… from a function?? (Hint: We already did, but… let’s see it again!)

See the Pen LRvwro by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Yep, piece of cake!

One can get pretty creative with assigning functions to variables and passing them around to other functions from which they can be returned. If you’re not careful (or maybe if you just want to have a bit of fun!), the rabbit hole can get pretty deep, pretty quickly! Consider this… a function can be passed to itself and even returned from itself!

Excellent! But okay… who cares if JavaScript functions are first-class objects? What does it matter?

The beauty of JavaScript functions enjoying first-class citizenship is the flexibility it allows. Functions as first-class objects opens the doors to all kinds of programmatic paradigms and techniques that wouldn’t otherwise be possible. Functional programming is one of the paradigms that first-class functions allow. Additionally, listening for and handling multiple events by passing callback functions is a useful feature within JavaScript and is achieved by passing a function as an argument to the document object’s addEventListener method. The process would not be nearly as elegant if functions were not granted first-class citizenship within the language. Furthermore, the practices of closure and partial-application/currying would not be possible within JavaScript if functions didn’t enjoy the status of first-class.

In summation, with functions being first-class objects within JavaScript, developers are able to do all kinds of interesting things and explore all sorts of programming paradigms that wouldn’t be otherwise be possible. It is in part due to this functional first-classness that JavaScript has become the powerful and prolific language that it is today.

Thanks for reading!