About the Author:

Front-End Development Explained for Non-Developers (part 1)

January 29th, 2020

Front-end development is defined, by Wikipedia, as the “practice of producing HTML, CSS and JavaScript for a website or web application so that a user can see and interact with them directly.” Most people can make sense of basic HTML, CSS, and JavaScript (and that used to be enough). But in the last 5-10 years, front-end development has evolved and splintered into a miscellany of frameworks, libraries, build-tools, command line tools, and new languages.

This plethora of technologies makes it challenging for developers and next to impossible for lay people to follow this field. This post will attempt to explain the landscape of front-end development technologies (as of mid-2015) for a non-developer audience.

Part 1 will cover Libraries and Frameworks. Part 2 will cover build tools, command line tools, and new languages. Part 3 will provide 3 pieces of recommended reading.

Libraries

There’s an organization in Denver, Colorado called the Denver Tool Library. For a subscription fee, they let members borrow some of their 2000 different tools. People can come in to chisel wood, test circuits, or maybe take a tool out to use in their garden. The library offers specific tools with specific functionality that can be used as many times as members need.

Programming libraries work very much in the same way as a physical tool library. Libraries like jQuery, Handlebars, Underscore or Backbone give developers specific functions, methods, and objects they can use to achieve a particular task in their code. With one command or <script> tag, developers can bring a library in and have immediate access to its tools.

The library that has had the largest impact on web development in the last 10 years is jQuery. Among other things, jQuery simplifies creating JavaScript across browsers.

Handlebars is a “semantic web template system”. Template systems make it easy for developers to put dynamic content into a static page a user sees. {{ Curly Brackets }} (aka sideways mustaches) are put into the HTML for dynamic content. Handlebars swaps out values between the curly brackets with content from the program. An example of this in action:

This HTML table…

<tbody>

{{#users}}

<tr>

<td>{{fullName person}}</td>

<td>{{jobTitle}}</td>

<td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td>

</tr>

{{/users}}

</tbody>

…will become this table with the help of Handlebars. The brackets get filled in with dynamic content:

Underscore takes a different spin on the tool library metaphor. Underscore used to call itself ‘a utility-belt library’ for JavaScript. Underscore gives developers shorter, faster ways of doing common tasks like looping over an array or object (which are collections of data in JavaScript). Normal JavaScript provides a way of doing this but a library like Underscore (or Lodash) provides a shorter/simpler way of doing so.

Backbone is a library that makes it easier to better organize applications. Backbone is usually used with Underscore and jQuery, and sometimes with Handlebars to form a complete application framework. An application framework usually handles a lot of the common tasks in web development like handling HTTP requests, routing, organizing business logic, and views the clients will interact with. We’ll go over frameworks in the next section in more detail.

React is the hot library of 2015. React came out of Facebook’s struggle to get the Like Button count to work well. When people would push it, it was hard to get the like count right. React offers a new (and faster way) to create data-driven interactive user interfaces. It is actually used in production for hundreds of millions of users (Instagram/Facebook) so even though it’s new, it has been thoroughly ‘battle tested’.

Photo, Phone, Android, Instagram, User, Smartphone

React in action

The Frameworks

A framework is typically something that provides a structure or way of organizing something. A web application framework, like Ember or Angular, saves developers from having to set up common web development structures/tasks on their own.

Think of a framework like a prefab home. Prefab homes come with the most of the ground plan laid out. The electrical wiring, framing, drywall, and plumbing are generally installed and ready to go. The homeowner then customizes the home’s interior suit their tastes (colors, textures, floors, appliances). The homeowner still could tear down the walls and rework the structure but generally they will go with the defaults.

This metaphor has its limitations but think of a web framework as providing a starting structure and set of defaults within which the developer can make an application.

Angular has become, by far, the most popular JavaScript framework in use (as of 2015). Angular handles tasks like connecting to a database, allowing the user to interact with information on the page, and handling the URL routing (in the address bar). Angular makes it simple to create what are called Single Page Applications (SPAs). If you’ve used Google Maps or Gmail, you’re used to a using a page that updates without refreshing the entire page. It does this by using a technology called Ajax.

Ember is another JavaScript framework that gives developers a scaffolding and structure to develop applications. Ember has a number of ‘opinions’ (conventions) that are meant to increase developer productivity. In theory, this should make it easier for developers to join an Ember project than an Angular project. The tradeoff of this is that some feel restricted by it’s enforced structure.

Bootstrap and Foundation are front-end frameworks that focus on the look and feel of a site. Both can be utilized to easily develop good looking sites that work well across different screen sizes. Each gives you pre-defined CSS and HTML components. A Bootstrap component would be a something like this piece of HTML:

<ul class="nav nav-pills"> 
<li role="presentation" class="active"><a href="#">Home</a></li> 
<li role="presentation"><a href="#">Profile</a></li> 
<li role="presentation"><a href="#">Messages</a></li> 
</ul>

This allows a developer to quickly get a navigation menu that looks like this:

By using Bootstrap/Foundation, developers can avoid having to reinvent the wheel when they need something common like a navigation menu, progress bar, or drop-down menu.

Bootstrap is now used on nearly 10% of internet sites. You can see a variety of sites that use Bootstrap at their showcase site.

Google Trends Proxy on Framework Popularity

Summary

This post gave a high level explanation on libraries and frameworks. Hopefully, you have a better sense of how each work now. Part 2 of this blog series will explore and explain how build tools, command line tools, and new languages work in front-end development.

About the Author:

How to Build a Simple Chat App with React Native and Firebase

November 30th, 2017

Nick is a mobile developer with wide experience in building iOS and Android applications at RubyGarage. He enjoys researching tech topics and sharing his knowledge with other developers.

In mobile development, cross-platform applications are appreciated for their short development cycle, low cost, and quick time to market in comparison with native apps.

One popular framework that enables developers to build hybrid mobile apps is React Native. React Native was created by Facebook developers during a hackathon back in 2013. Since then, the framework has become a core technology for numerous mobile applications including Instagram, Skype, Tesla, Airbnb, and Walmart. (more…)

About the Author:

Manage Your JavaScript Canvas Elements

November 27th, 2017

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.

About the Author:

Official Vue Projects You Probably Don’t Know About

November 21st, 2017

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.

About the Author:

Simplifying Your Workflow With Vue Development Tools

November 9th, 2017

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.

About the Author:

Falling Back in Love with the Front End: An Interview with Azat Mardan

May 18th, 2017

Azat Mardan teaches multiple JavaScript courses for DevelopIntelligence and appendTo. When he’s not teaching, he is a Technology Fellow at Capital One and a prolific technical writer. He has 12 Javascript books published, including React Quickly and Full Stack JavaScript.

We interviewed him about his experience with React.

appendTo: Hi Azat, tell us about your experience with React. When did you get started and what got you into it?

Azat: The first time I’d heard about React was three or four years ago. I was teaching at a coding bootcamp and we would usually find out about new stuff before it hit the mainstream.

I didn’t jump into it right off the get go. I was just observing it and seeing what would happen with it. Then, around two years ago, it became clear that React was becoming extremely popular. I would go to conferences and all people talked about was React and ES6. So I decided it was time to write a new book. I approached Manning Publications and offered to author a book and they agreed and I started writing React Quickly.

React is now totally mainstream and we have a whole ecosystem of libraries and components around React. React has grown well beyond just building web apps and has generally changed the way people develop, on the web and off the web.

appendTo: What did you enjoy about writing a book on React?

Azat:  I learned React, inside and out, while writing this book. One of the things I’m most excited about is that React is helping to bring back functional programming.

There used to be a feud between object-oriented programming and functional programming back in the day. Object-oriented programming won this feud and OOP dominated the landscape for a long time. But now, functional programming is making a comeback.

I find functional programming just keeps things simpler and more manageable and has very little overhead. It lets me just get to solving my problem instead of creating and co-creating, classes and interfaces, extending those interfaces inside the class, et cetera, et cetera.

It’s amazing to see such a resurgence of interesting in functional programming. There’s so many new books on functional programming, articles on functional programming, and online courses. It’s great for engineers and developers to be learning more about functional programming. Hopefully the new languages like Elm and some other pure functional languages will continue to bleed into the React world and related libraries.

appendTo: What are your general thoughts on React?

Azat: If someone is not using React, they should definitely give it a try. React got me back into front-end development, period.

A few years ago, I was ready to quit frontend development altogether. I didn’t want to learn Angular. I avoided Angular on purpose, it just looked weird to me. It forced you to learn so much Angular-specific domain knowledge and so much knowledge on how the directives work. I just didn’t want to become an Angular developer. I wanted to remain a JavaScript and Node developer and avoid learning some very specific narrow framework.

But when I discovered React, it totally reignited my passion for the frontend. React was fun! I built a relatively large project called MongoUI, it’s a visual dashboard for MongoDB, where you can create documents, update documents, search for documents. So instead of using a console, you can just use a graphical interface. I used React for this and it was relatively easy. I would create a small component, reuse it in many other places and it was magical. Front-end development with React is so much simpler and easier now.

appendTo: Well that sort of answers my next question. Why has React grown so big, so quickly?

Azat:  Well, it wasn’t that quickly really; it was a few years. But React was a paradigm shift. It shifted the fundamentals. Once people started using it, they didn’t want to go back to MVC or templates. You don’t want to jump between HTML and JavaScript anymore. You want all the code for one piece of UI to be in one place. In React components, you describe your UI just once and then whatever dynamic code you need to put, you put it right there in the component. It is self-contained functionality and React takes care of maintaining internal state and syncing the state with the UI. React took off, in short, because of simplicity, ease of development, and developer experience.

In a way, the evolution seems to go in a circles. We started with simple Vanilla JavaScript for apps. Then we have jQuery. Writing lots of jQuery ends up with spaghetti code. Then we decided we needed some MVC Frameworks, because MVC was considered good in other languages. MVC frameworks started small like Backbone and then they become complex like Ember and Angular. Now we’re back to the just the simple.

React gave us components, the virtual DOM, diffing the virtual DOM from the real DOM and not manipulating it directly. React didn’t invent components but it did make them more popular. Add to this all that, with React, you don’t need to learn a new framework (like in Angular), you can just use JavaScript.

With React, it’s fairly easy to get started by reading a few blog posts and starting small. It’s also fairly easy to integrate React with legacy code or existing jQuery code.

appendTo: We wanted to learn a bit more about the React inspired libraries like Inferno and Preact. Where do they fit in?

Azat: Another great thing about React is that the enormous community keeps forging ahead. There are people still working on and improving React Core and React Router. But now there are these new libraries, like Inferno and Preact, which can replace React Core. These new libraries are pared-down, lighter-weight, and ultimately, faster substitutes for React core. They allow you to keep all your existing React components, method names, and class names, but get a faster end product. So, for example, if you’re not going to use a specific part of React like property types, you can use Preact/Inferno.

appendTo:  What are some of the benefits of having a lightweight React?

Azat:  By having your app load faster, it lets more people around the world use and enjoy it. Many of them might still be using 3G networks. A lot of sites have gotten really heavy and libraries like Preact/Inferno allow you to reach a broader audience. Visitors can notice delays of 100 milliseconds and the longer you make people wait, the more traffic you lose. Less traffic means less customers and that translates to money for businesses.

appendTo:  How hard is it to switch our React core for Preact or Inferno?

Azat:  In some cases, it could be just one line of code. Instead of importing React, you would import Preact. It would be one line of code or a couple lines of code, in many cases. Your other React components code stays the same, you just use the different library for the core.

About the Author:

Front-End Development Explained for Non-Developers (part 3)

September 3rd, 2015

This last post in the series of 3 will curate 5 interesting resources on front-end development you should check out if you’d like to know more on the field.

The JavaScript World Domination

This post details the history of Javascript from something that would animate web pages to becoming the dominant programming language.  It alludes to where Javascript might be going and talks about many unexpected use cases of the language.  It does a good job at staying high level and is approachable for non-technical audience.

(more…)

About the Author:

Front-End Development Explained for Non-Developers (part 2)

September 3rd, 2015

This blog series is explaining common front-end development technologies for a non-technical audience. Part 1 of this series explored front-end libraries and frameworks. This post will explain/explore build tools, command line tools, and new languages.

Build Tools

When developers create applications, there are numerous tasks involved. These tasks include setting up their codebase, downloading libraries, or preparing their application for production deployment. These tasks can be done manually using the command line, a package manager (like NPM), or manually creation/coding. But running these tasks manually can become repetitive and disorganized. Developers hate repetition (that’s what computers are for) so they create tools to handle this anytime they can. The tools, in this case, are called task runners or build automation tools.

Grunt and Gulp are the most commonly used build automation tools. Grunt got an earlier start but Gulp has quickly become more popular. Think of build tools as “programming to setup for programming”. A common task in Grunt/Gulp would be to ‘lint’ the code upon saving. Linting code is the process of checking it for proper syntax/styling. This is one way to reduce bugs and make code more readable. Grunt/Gulp are commonly used to run such tasks as minification, concatenation, clean up file locations, and compile one type of file to another.

An easy way to imagine Gulp is to picture it as a sort of old-school pneumatic tube

system. Gulp is a way to pipe files from one location to another. The difference is that Gulp uses one or many plugins in the middle to make changes to the file before delivering it to it’s destination.

Broccoli is similar and newer than Grunt/Gulp. It does tasks differently and offers a more concise syntax and increased performance. Broccoli’s is supposed to be especially helpful when projects grow in size/complexity. Grunt and Gulp files can quickly become difficult to wrangle and Broccoli’s tree/folder based tasks supposedly shine here.

Yeoman has a set of ‘generators’ that allow for quickly setting up / scaffolding a project. Rather than taking the time to create folders for your HTML, JavaScript, and CSS, Yeoman will do this for you. You can then tweak the setup to your liking/needs.

Command Line Tools

In 2015, most development projects require a lot of external libraries (you know what a library is now, right?). To use jQuery, for example, the developer needs to go to jQuery’s site, download the source code, put it in the right folder, and include the <script> tag in their code to bring jQuery in. This quickly gets tedious as a project needs many libraries. Furthermore, it becomes difficult to keep track of which version is needed where.

An example of how libraries are included into a project

Command line tools like Bower and the Node Package Manager (npm) allow for libraries to be installed using the command line. A simple command like bower install jquery will go fetch the jQuery source code and put it into the bower_components folder, stored locally. Now the index.html file will look something like this:

<script src="bower_components/jquery/dist/jquery.js"></script>

<script src="bower_components/underscore/underscore.js"></script>

<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>

<script src="bower_components/angular/angular.js"></script>

<script src="bower_components/angular-route/angular-route.js"></script>

<script src="bower_components/angular-resource/angular-resource.js"></script>

NPM can do everything that bower can and more. There 70000+ npm modules to the Bower’s 10000+ packages. Npm needs Node.js to run and many projects don’t use node. Npm also installs many more dependencies (think Libraries that depend on Libraries) when you install something with npm. Bower will, supposedly, install fewer dependencies and therefore take up less space than npm modules.

It’s a bit trickier to think of metaphors for command line tools. But, imagine, you’re a dentist working on someone’s teeth. You merely have to open your hand and say the tool you need and an assistant puts in it in your hand for you. This is what Bower and Npm are to a developer. In a command or two they have quick access to the tools they need.

Languages

JavaScript and CSS are default languages that are used in webpages. However, they each have their own drawbacks in terms of syntax, whitespace, and aesthetics. For this reason, developers invented new languages and ‘preprocessors’ that they develop in. They then take these new languages, like CoffeeScript or Less, and compile/convert them into JavaScript, HTML, or CSS. The newer languages are easier to develop in but must ultimately become what the browser can read.

CoffeeScript

CoffeeScript is a programming language that ‘transcompiles’ (converts) to JavaScript. CoffeeScript is a cleaner prettier version of JavaScript. It has a ‘leaner syntax’ that makes it easier to read. Here’s a quick example from the CoffeeScript site:

Looping over an Array example in JavaScript (a common task):

cubes = (function() { 
var i, len, results; 
results = []; 
for (i = 0, len = list.length; i < len; i++) { 
num = list[i]; 
results.push(math.cube(num)); 
} 
return results; 
})();

The Equivalent in CoffeeScript:

cubes = (math.cube num for num in list)

This is one small example of how using something like CoffeeScript makes developers’ jobs easier.

Typescript

Typescript is another new language that converts to JavaScript. One of the biggest potential drawbacks of JavaScript is its ‘weak typing’. Weak typing basically comes down to not being able to tell when a piece of data is a string (text) vs. a number. Typescript has stronger typing (hence ‘Type’ in the name).

Typescript also offers some advanced (futuristic) JavaScript functionality that isn’t supported by most browsers yet. Typescript offers features (e.g. modules, classes, mixins) that will come with the next version of JavaScript, ES6. Typescript will convert back to normal JavaScript and work in today’s browsers. Typescript offers JavaScript’s future, today.

Less, Sass, and Compass

Less, Sass, and Compass are all languages that can be compiled to CSS. They are to CSS what CoffeeScript/Typescript are to JavaScript. Less, Sass, and Compass improve the process of writing CSS.

For example, say a developer is going to use the same color across their application. Instead of writing out the hex color code (e.g. #000080) multiple times, they can declare it once as a variable then use that variable across the application. When that Less, Sass, or Compass is compiled later, that hex code will put in across the CSS.

Think of Less, Sass, and Compass as using programming in CSS. They give you functions, variables, and logic to make stylesheets easier to write, maintain, and understand. Here’s a quick example in Sass from this excellent post:

$container-width: 100% - 20px;

This is assigning a value to the variable of “container-width”. Containers are common HTML objects. This variable will be assigned however many pixels is currently 100% (width) minus 20 pixels. This spares the designer/developer from having to go figure out what the current proper width is and subtract 20px and put that value in. When something changes in the styles, the changes will propagate dynamically across the stylesheet (vs. having to go do all the math again). This small example shows how something like Sass makes writing styling much easier.

Summary

This post covered build tools, command line tools, and new languages. Most of these tools didn’t exist 5 years ago and none existed 10 years ago. It’s easy to get lost in their cryptic names and acronyms. Simply remember that they all exist to make developing and maintaining applications easier. In 5-10 years, you’ll have a new set of technologies to learn up about! They will have the same purpose as well.

The final post in this series will curate some introductory level writing on front-end development. These 5 posts were selected to be generally approachable to a non-technical person. They will allow you to appreciate how far this field has come and how exciting it is now.

About the Author:

Front-End Development Explained for Non-Developers (part 1)

September 2nd, 2015

Front-end development is defined, by Wikipedia, as the “practice of producing HTML, CSS and JavaScript for a website or web application so that a user can see and interact with them directly.” Most people can make sense of basic HTML, CSS, and JavaScript (and that used to be enough). But in the last 5-10 years, front-end development has evolved and splintered into a miscellany of frameworks, libraries, build-tools, command line tools, and new languages.

This plethora of technologies makes it challenging for developers and next to impossible for lay people to follow this field. This post will attempt to explain the landscape of front-end development technologies (as of mid-2015) for a non-developer audience.

Part 1 will cover Libraries and Frameworks. Part 2 will cover build tools, command line tools, and new languages. Part 3 will provide 3 pieces of recommended reading.

Libraries

There’s an organization in Denver, Colorado called the Denver Tool Library. For a subscription fee, they let members borrow some of their 2000 different tools. People can come in to chisel wood, test circuits, or maybe take a tool out to use in their garden. The library offers specific tools with specific functionality that can be used as many times as members need.

Programming libraries work very much in the same way as a physical tool library. Libraries like jQuery, Handlebars, Underscore or Backbone give developers specific functions, methods, and objects they can use to achieve a particular task in their code. With one command or <script> tag, developers can bring a library in and have immediate access to its tools.

The library that has had the largest impact on web development in the last 10 years is jQuery. Among other things, jQuery simplifies creating JavaScript across browsers.

Handlebars is a “semantic web template system”. Template systems make it easy for developers to put dynamic content into a static page a user sees. {{ Curly Brackets }} (aka sideways mustaches) are put into the HTML for dynamic content. Handlebars swaps out values between the curly brackets with content from the program. An example of this in action:

This HTML table…

<tbody>

{{#users}}

<tr>

<td>{{fullName person}}</td>

<td>{{jobTitle}}</td>

<td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td>

</tr>

{{/users}}

</tbody>

…will become this table with the help of Handlebars. The brackets get filled in with dynamic content:

Underscore takes a different spin on the tool library metaphor. Underscore used to call itself ‘a utility-belt library’ for JavaScript. Underscore gives developers shorter, faster ways of doing common tasks like looping over an array or object (which are collections of data in JavaScript). Normal JavaScript provides a way of doing this but a library like Underscore (or Lodash) provides a shorter/simpler way of doing so.

Backbone is a library that makes it easier to better organize applications. Backbone is usually used with Underscore and jQuery, and sometimes with Handlebars to form a complete application framework. An application framework usually handles a lot of the common tasks in web development like handling HTTP requests, routing, organizing business logic, and views the clients will interact with. We’ll go over frameworks in the next section in more detail.

React is the hot library of 2015. React came out of Facebook’s struggle to get the Like Button count to work well. When people would push it, it was hard to get the like count right. React offers a new (and faster way) to create data-driven interactive user interfaces. It is actually used in production for hundreds of millions of users (Instagram/Facebook) so even though it’s new, it has been thoroughly ‘battle tested’.

Photo, Phone, Android, Instagram, User, Smartphone

React in action

The Frameworks

A framework is typically something that provides a structure or way of organizing something. A web application framework, like Ember or Angular, saves developers from having to set up common web development structures/tasks on their own.

Think of a framework like a prefab home. Prefab homes come with the most of the ground plan laid out. The electrical wiring, framing, drywall, and plumbing are generally installed and ready to go. The homeowner then customizes the home’s interior suit their tastes (colors, textures, floors, appliances). The homeowner still could tear down the walls and rework the structure but generally they will go with the defaults.

This metaphor has its limitations but think of a web framework as providing a starting structure and set of defaults within which the developer can make an application.

Angular has become, by far, the most popular JavaScript framework in use (as of 2015). Angular handles tasks like connecting to a database, allowing the user to interact with information on the page, and handling the URL routing (in the address bar). Angular makes it simple to create what are called Single Page Applications (SPAs). If you’ve used Google Maps or Gmail, you’re used to a using a page that updates without refreshing the entire page. It does this by using a technology called Ajax.

Ember is another JavaScript framework that gives developers a scaffolding and structure to develop applications. Ember has a number of ‘opinions’ (conventions) that are meant to increase developer productivity. In theory, this should make it easier for developers to join an Ember project than an Angular project. The tradeoff of this is that some feel restricted by it’s enforced structure.

Bootstrap and Foundation are front-end frameworks that focus on the look and feel of a site. Both can be utilized to easily develop good looking sites that work well across different screen sizes. Each gives you pre-defined CSS and HTML components. A Bootstrap component would be a something like this piece of HTML:

<ul class="nav nav-pills"> 
<li role="presentation" class="active"><a href="#">Home</a></li> 
<li role="presentation"><a href="#">Profile</a></li> 
<li role="presentation"><a href="#">Messages</a></li> 
</ul>

This allows a developer to quickly get a navigation menu that looks like this:

By using Bootstrap/Foundation, developers can avoid having to reinvent the wheel when they need something common like a navigation menu, progress bar, or drop-down menu.

Bootstrap is now used on nearly 10% of internet sites. You can see a variety of sites that use Bootstrap at their showcase site.

Summary

This post gave a high level explanation on libraries and frameworks. Hopefully, you have a better sense of how each work now. Part 2 of this blog series will explore and explain how build tools, command line tools, and new languages work in front-end development.