Modern Web Development & Practices

Param Singh
paramsingh_66174
Published in
16 min readFeb 19, 2017

The web platform has been expanding just like the Universe as per the Big Bang Theory. Every day or the other we hear about a new library or tool that’s there on npm or github. Gone is the time when all we needed to create a web page was a primitive HTML page with some inline CSS and a bit of JavaScript to add “interactivity” to the web page. The contemporary era demands way more than this. Hence, leaving us with a myriad of Frameworks and libraries one day or the other. I love this power of Open Source, it’s created for us and by us. But, these numerous tools and libraries might leave one overwhelmed to choose one over the other. So, without saying much here I’m sharing my preferred practices for building kickass development environment and end products.

Editors

Editors being the important part of our lives as developers. We should be choosy enough to pick the best one for our needs. Below are a few popular ones.

Sublime Text 3: As they say, “The text editor you’ll fall in love with”. Indeed, its the one and personally my favourite. Why? Because, it’s simply really fast and for a multi-tasker like me who keeps a number of projects open at a time, it bears me well (unlike other text editors :P). Not only this, it has a really good open source support for plugins, be it code formatting, theming, auto completion etc. All of this at a minimal cost of size.

Sublime Text 3 Editor

Atom: Another good open source editor to fit your needs is Atom built using electron and hence “hackable to the core” in their words. Just like Sublime it has good support for plugins and themes. Also, it’s crude theme is very cute and luring. But do not fall for this cuteness if you plan to use it for multiple projects at a time. I used it for some time and it used to crash as it couldn’t hold the burden like Sublime does. That said, one reason I would favour using it over Sublime would be it’s support for in built terminal

Atom Editor

WebStorm: It’s more than just an editor since it’s an IDE (Integrated Development Environment) by JetBrains with a lot of features like code completion, breakpoint debugging, tracing and profiling etc and yeah an in built terminal too (pretty much like Eclipse for web). Only thing is that it’s paid and again good things come at a cost of memory.

IntelliJ — WebStorm

Vim: Say What? Yeah, Vim it is. Let’s never undermine the power of this cool text editor with unique support for those cool commands to make you work like a boss. It’s notoriously difficult to master initially, but once mastered, there’s no going back. And who said it can’t look pretty!

Vim

JS Frameworks & Libraries

Frameworks are a great way to save your time and sweat by providing standard scaffolded structures already cooked for you. In most of the organisations where there are high demand of build and ship kind of products, frameworks fit best. While there are a lot of JS frameworks already, plus more coming up day by day. It might seem overwhelming for a person to start on one of them. The prominent ones being Angular, React, Polymer, Vue, Aurelia, Meteor, Ember. Without favouring anyone of them, I’ll discuss the ones I like the most

React JS: Although a library, not a framework. But immensely popular and with a really good community support, React has been the first choice for UI developers because of the advancements it offers in terms of Universal

ReactJS

Isomorphic Apps (Server Side Rendering), good support for native apps using React Native and not to mention the speed it offers over the conventional DOM operations exploited by libraries like jQuery. It uses the concept of Virtual DOM and Smart Diff Algorithm which makes it fast and hence popular. Also, very easy to pick up if you know JS. Only problem is it’s a bit perplexing to setup for beginners since a myriad of boilerplates exist for the same, some using browserify, some using webpack. Also, the folder structure might vary from project to project. Although, there are tools like react-cli available.

Angular JS: The framework that revolutionised the way we used to write frontend code introducing the MVVM design pattern into the mix. Backed by Google, Angular 1.x has been really popular ever since it was launched in 2011. It happened in mid 2015, React started to take over the prevalence providing better stuff than Angular. Angular folks in an attempt to be at par with React’s increasing popularity, released Angular 2 last year claiming it to be 5x times faster than Angular 1.

Angular 2

And it looks nothing like Angular 1 cause it uses TypeScript and RxJS too. Due to this, developers fear about it’s learning curve. And yes, having doing a project using it at the time of writing this post, the learning curve is indeed steep. It’s not as easy as pie if you’re completely agnostic towards using any JS frameworks or JS itself before. But after experiencing it, I must say, don’t care about what critics have to murmur about TS, I love it. I think it’s a very nice move by Angular Team to use it for Angular 2 due to the features it offers like type safe code, generics etc. In short, it eliminates a lot of code like this:

if(typeof name !== ‘string) throw ‘Name should be string’

Simply, specifying the datatypes while declaring variables will do the job.

isPristine: boolean = true;

Plus, another thing is using an standard cli tool as Angular CLI, it saves you from the pain of scaffolding and generating the components on the fly.

VueJS: Another new kid on the block that’s setting fire. The Vue folks claims it to be faster than React and every other framework.

VueJS

Just like React, it uses Virtual DOM. In fact, it uses a more optimised and light weight version of v dom, a fork of snabbdom that reduces the JS computations. Another good reason to choose it is that unlike React, that introduced JSX, yet another thing for you to learn, Vue uses plain standard HTML templates which are easier to understand for a beginner.

<template><div class="list-container"><ul v-if="items.length"><li v-for="item in items">{{ item.name }}</li></ul><p v-else>No items found.</p></div></template>

More goodness comes with the Component Scoped CSS it offers. Since, building web components is always a pain when it comes to styling. If you’re using React, you have to depend on third party tools like Radium. More to that is, it includes challenges like one can’t use Media Queries or pseudo css selector like hover, active etc in them. Vue seems to solve all these challenges well.

<style scoped>@media (min-width: 250px) {.list-container:hover {background: orange;}}</style>

Polymer: The Polymer Project is an open source project by the Google team that utilised the full benefits of HTML Imports. It introduced to us the notion of reusable Web Components i.e self contained grouped elements supposed to perform certain task.

Polymer

It’s api consists of a lot of elements like Paper Elements for material components, iron elements (Core elements), gold elements for E Commerce (Credit Card & purchases stuff), Neon elements for animations and effects and a lot more.

Vue is related closely to Polymer. But

The biggest difference is that Polymer is built upon the latest Web Components features and requires non-trivial polyfills to work (with degraded performance) in browsers that don’t support those features natively.

More on this available here.

CSS Preprocessors

Writing crude CSS for smaller projects makes sense where we make a main.css or home.css kind of file and include it directly in our index.html, but as your project grows and also with the increasing trend of web components, it becomes necessary to modularise and introduce some programming features like variables declarations, functions or macros (mixins in Sass) etc into it. Css Preprocessors like SASS, LESS, Stylus, Myth solves these problems. My favourite one being SASS.

Sass

SASS: Short for Syntactically Awesome Style Sheets, SASS is indeed awesome. You can declare variables, use imports, create mixins very handy for generating things like vendor prefix css properties, media queries, text truncation and a lot more. You can also use on the fly computation of values for certain css properties. There are two ways or versions to use SASS. SASS itself which is the original syntax that uses indentation for block scoping as.

$serif-font-stack: "Georgia", "Times New Roman", serif
$monospace-font-stack: "Cousin", "Courier"
body
font: normal 18px/22px $serif-font-stack
pre, code
font: 600 bold 18px/22px $monospace-font-stack

The other more popular version is called SCSS, which is similar to native CSS as:

$serif-font-stack: "Georgia", "Times New Roman", serif;
$monospace-font-stack: "Cousin", "Courier";
body {
font: normal 18px/22px $serif-font-stack;
}
pre, code {
font: 600 bold 18px/22px $monospace-font-stack;
}

Template Engines

Consider you’re creating a portfolio static website for yourself and you have to create a list of your projects each consisting of a title, a description and maybe some tags. Each project node in html has the similar syntax, only the fields like title, description and tags are dynamic. So, it’d be wiser to create a template and iterate it using a loop construct supplying the dynamic values in each iteration. Although, you can accomplish the same using VanillaJS too, but template engines like Mustache, Pug (formerly known as Jade), Handlebars make it fairly easier for you providing you to write html like syntax with placeholders embedded in them for dynamic values along with the loop constructs too.

Handlebars

Below is snippet of Handlebars template.

<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>

And to compile it passing the data or dynamic values, we can do:

var source   = $("#entry-template").html();
var template = Handlebars.compile(source);

All the JS frameworks we discussed above, have their own templating engines built in.

Redux

Redux

As the official docs say

Redux is a predictable state container for JavaScript apps

Hmm, perplexing for a newbie to understand. Let me explain a bit more about it with a practical example. Redux is nothing but a design pattern in my eyes to manage the “state” of your application. Consider the following snapshot from one of my React app — Harp.

Harp — A progressive web app using React + Redux + ImmutableJS

What can you deduce about the current instantaneous state of the application from the given snapshot? Let me sum it down for you.

The search text is set to “ed sheeran”

Selected Artist is set to “Ed Sheeran” which holds information like artist name, genre tags, profile picture, number of followers etc.

The lower area holds a list of songs of the selected artist.

Considering the state of the player, the selected song is “Shape of You”, artist name is “Ed Sheeran”, audio is in play state, audio position is around 70%. Volume is set to 3 (although not visible here).

So, what I’m trying to explain is that the template is same, only on the basis of some criteria which is a route param like artistId in our case, the api call is fetching the details from Spotify API and populating the template with the “current state” or simply we can say the “data”. On this state if some event happens say the user seeks the player seek bar to 90%, the current state has to be updated by you by dispatching what is called an Action in Redux jargon. It could be any event, triggered by user or by network (Ajax call), player event etc.

There are three golden principles of Redux that it follows:

  1. Single Source of Truth: Any change in the state throughout the application that happens has to be updated in the state by dispatching an Action. The changes from the state are in turn subscribed by the components to update their content or bindings.
  2. State is Read Only: You can’t or should not try to mutate the state directly. The ethical way to do that is by dispatching an action. In response to that action, a function called Reducer updates the state.
Redux Data Flow

3. Changes are made with pure functions: The Reducer function we discussed above is a Pure Function. We read about pure functions in Mathematics, functions like sin(x), cos(x) are pure. We know that the value of sin 30 is going to be 1/2 , no matter what. Given a certain input, it’s output is the same always unlike Impure functions like rand() or printf(). Coming back, the reducer is a function which takes two parameters: Previous State and an Action and returns a completely new state without mutating or changing the previous state since it’s a pure function.

Redux is a very cool state management library as of now and I highly recommend using it. It’ll save you from cooking spaghetti code and unpredictable errors. Also, debugging will be a breeze with the really awesome dev tools created by community. Here’s one really popular, redux-devtools with features like Time Travel Debugging. Thanks to Dan Abramov, the creator of Redux himself.

Redux Dev Tools Snapshot

ImmutableJS

ImmutableJS

Talking in tandem with our discussion on Redux, we noticed a little problem with it. As we mentioned, the reducer is a pure function which takes the previous state and returns an entirely new state object with the changes done for a given action. Now, say your app state tree grows a lot over time. Creating such a huge state tree object every time is not economical memory wise. A solution to this is an attempt by Facebook devs with ImmutableJS. It enforces immutability and function purity in the very first place. It provides constructs like Map, Sets, List with a plethora of methods on them like underscore of lodash for data manipulation.

Since, our reducers in Redux has to be pure functions, if the state passed is immutable, one can’t even deliberately mutate it ever if we use Immutable.Map for the State being passed. In addition to this, the new change being done to the state doesn’t actually create a new object, instead it gives a reference to the new tree with a leaf attached to it. It’s called Structural Sharing. Thus, it helps avoiding memory leaks. There’s also another library supporting the same cause called MoriJS.

A reducer using Immutable construct looks something like this:

import { fromJS, Map } from 'immutable';import ArtistConstants from './ArtistConstants';const initialState = fromJS({
data: {
images: [{}],
genres: []
},
tracks: []
});
const ArtistReducer = (state = initialState, action) => {
switch (action.type) {
case ArtistConstants.SET_ARTIST_DATA:
return state.setIn(['data'], fromJS(action.payload))
case ArtistConstants.SET_ARTIST_TRACKS:
return state.merge(fromJS({
tracks: action.payload
}))
default:
return state;
}
};
export default ArtistReducer;

RxJS

RxJS

An API for asynchronous programming with observable streams

RxJS is a library or an implementation of Reactive Programming Paradigm which aims at managing the asynchronous behaviours of our application. It treats every event happening in the app as an Asynchronous Data Streams using the Push & Pull pattern, means you can create a source from where you can publish events based on some activity and there’s a sink in which you can subscribe or listen to those events and do some appropriate actions.

Reactive Programming Principle

If you are finding it confusing, below is a little but very useful example from one of my apps. So consider, there’s a “buy now” button on your app checkout page. The tester comes to you and reports that if the user taps this button very fast and continuously, say twice or thrice within a matter of seconds, multiple orders get created for that user. So, how can you handle such problem becomes very easy once you get a hold of Rx. You just need to convert the click event of the button into a Rx Stream and use throttle operator. What it does is, within an interval of 1.5 seconds, doesn’t matter how many time the user taps the button, it’ll be counted only as 1. The next event will be triggered only after 1.5 secs. Just what we need to avoid such silly user interaction problems.

Rx.Observable.fromEvent(ReactDOM.findDOMNode(this.refs._btn), 'click')
.throttle(1500)
.subscribe((event) => {
this.handleBuy(event);
})

The use of Rx is not only limited to this, there’s another very useful example from the Rx Docs

var input = document.getElementById('input');
var dictionarySuggest = Rx.Observable.fromEvent(input, 'keyup')
.map(() => input.value)
.filter(text => !!text)
.distinctUntilChanged()
.throttle(250)
.flatMapLatest(searchWikipedia)
.subscribe(
results => {
list = [];
list.concat(results.map(createItem));
},
err => logError(err)
);

Say you wanna create a search anything functionality using wikipedia api in your app. Triggering an Ajax call every time with an alphabet typed in the input box using the keyup event would not be a good idea. Also showing the user stale result of the previous call is also not good. RxJS provides us with really useful operators like distinctUntilChanged, throttle, flatMapLatest to cater to all our needs. The above snippet will help you only trigger an Ajax call when the user has typed some input (filter), the input is not similar to previous one (distinctUntilChanged, because arrow keys are also included in keyup event), only show latest results to the user (flatMapLatest) etc.

We’ve barely scratched the surface of Reactive Programming here. I recommend reading the full docs here for better understanding. The more you use RxJS in your app, more benefits you can observe.

Hot Module Replacement (HMR)

One of the coolest thing that has happened is HMR. Ah, no more annoying waiting times when you updated a little thing in your code and the whole app is recompiling and then you have to refresh it in the browser! So, much pain. Isn’t it? If you’re going through the same pangs, say aloha to HMR. Just try it once, and you’ll fall it love with it.

Hot Module Replacement Diagram

“Hot Module Replacement” (HMR) is a feature to inject updated modules into the active runtime.

Only problem is it’s a bit difficult to setup. I’ve used react-hot-loader again by Dan Abramov. If you’re facing issues integrating it, use this boilerplate already including all of the stack items we discussed above for a react project. https://github.com/paramsinghvc/react-boilerplate

Angular 2 also supports HMR. Here’s an implementation by AngularClass.

Task Runners

Task Runners are workflow management tools. With all of the above third party tools and libraries we discussed above, we need to compile them to something what our browser or rendering engine understands. For eg, your browser is not going to understand SASS or the code written in TypeScript or ES6 at all. It needs to be compiled. Also, it becomes very critical for you to bundle up your code and ship it to production server by applying Concatenation of files and subsequent Minification by removing comments, name mangling, white space removal, deduplication etc. Usually, we write shell scripts to accomplish such things which might get cumbersome at some point of time. Task Runners like GulpJS, GruntJS not only solves such problems but also provides you with a better management of your build configuration.

GruntJS

GruntJS: Introduced in 2012, it’s a quite old task runner that seems to have been replaced by Gulp now a days. It used configuration over code in a gruntfile.js included in your project root directory that allowed you use plugins to accomplish all the bric-a-brac tasks of your web app discussed above.

GulpJS

GulpJS: A widely used task runner that favours code over configuration using NodeJS kind of streams and modules. It provides almost all kind of functionality with its wide support of plugins all over npm. You name it and you’ll get it. Be it, css auto-prefixer, angular 1 dependency array injection, sass to css etc.

Webpack 2

Webpack: It’s exactly a task runner. Instead, it a module bundler. But in many cases it can be used as a substitute for task runners. It goes well with React Project, very easy to configure with again a very good support for plugins. With the release of Webpack 2 lately, there are features like Tree Shaking, Lazy Loading introduced for better optimisation of your app code for production environment.

There are several others like JSPM, Rollup, SystemJS etc that are worth checking out.

Conclusion

The web platform is really dynamic. One day or the other, there are tons of libraries and tools being produced by the community. It’s impractical to use all of them obviously. But the technologies we discussed above are some of the popular ones and widely accepted by the developers. Also, these are the bits and pieces I’ve found from my experience with various frameworks and libraries. It’s nothing like you can’t use TypeScript or RxJS in React project. And if you haven’t used any of these, you MUST consider using it in your next project. Cause, its not only good for your users but also for your development workflow. As they say “Necessity is the mother of invention”. These cool technologies have been invented for people like us and by us. So, we should brace ’em and start using them happily.

Hope you enjoyed reading it, kindly leave your comments and feedback.

Thanks!

--

--

Param Singh
paramsingh_66174

Senior Front-end Engineer at AWS, Ex-Revolut, Flipkart. JS enthusiast. Cynophile. Environmentalist