About the Author:

Where Did Vue.js Come From?

March 5th, 2017

Vue.js’s popularity has been climbing pretty fast. It has about 3/4 the number of stars on Github as React, and more than double the stars of Angular. The watchers and forks are also pretty comparable. And the while Vue.js hasn’t nearly caught up yet, you can see a definite trend of relatively rapid growth on Google Trends that is comparable to the growth of React and Angular earlier in their lives.

graph

Angular is still on top, but Vue.js is rising quickly

There needs to be a reason that Vue.js is growing rapidly, especially when the JavaScript framework ecosystem is already filled with plenty of great frameworks. Vue.js doesn’t truly offer anything that other frameworks don’t already have, but it does bring together features from other frameworks in a unique way that may be a better combination. Which of these features did Vue.js glean from other frameworks, and from which ones?

Component-Based

“Component-based” means that the framework is based around creating, composing, and nesting user interface building blocks called components. These components encapsulate everything to do with themselves rather than moving the logic out to a controller or something similar. Components go beyond view objects because they because they can be used directly in the templates as if they were HTML elements:

 

Some Title

Hello

 

React is likely the primary source of inspiration for Vue.js in this area, though you could argue that Polymer and/or Web Components should be considered the inspiration here. I lean toward React primarily because Polymer is designed to actually create custom elements to be used directly in the HTML, whereas React and Vue.js use their components as if they were custom elements only in their templates (JSX in React’s case) and use the rendering engines and template compilers to only give the browser HTML elements that it already knows.

In the end, though, it doesn’t really matter who the idea was stolen from. What matters is that the declarative nature component-based systems are far simpler to use and compose than the imperative, old-school views and sub-views that came with Backbone.js and similar MV* frameworks.

Directives

Directives are a means of control flow and DOM manipulation that are built into the templates and look like HTML attributes. For example:

    • {{ item.message }}

 

 

The v-for attributes is a directive that loops through items so they can all be displayed in li elements. Angular and Aurelia do very similar things. In Angular it would look like this:

    • {{ item.message }}

 

 

And Aurelia looks like this:

    • ${ item.message }

 

 

If you don’t have this kind of control capability embedded in the template syntax, the code becomes more difficult to read because you need to switch back and forth between the template syntax and the JavaScript’s syntax. Once again, the code is becoming more declarative instead of imperative.

Single, HTML-Based Component File

I wrote an article entirely about Vue’s Single File Components and the benefits they provide. It turns out, though, that Vue.js wasn’t the originator of this idea, at least not entirely. Vue.js stole this from Polymer/Web Components. Right on Polymer’s home page, halfway down the page you’ll find an example that looks remarkably similar to a Vue.js Single File Component:

<dom-module id="contact-card">
  <style>...</style>
  <template>
    <content></content>
    <iron-icon icon="star" hidden$="{{!starred}}"></iron-icon>
  </template>
  <script>
    Polymer({
      is: 'contact-card',
      properties: {
        starred: Boolean
      }
    });
  </script>
</dom-module>

Of course, Vue.js goes beyond this by allowing you to use alternative languages for the CSS (Sass, Less, Stylus, CSS Modules), HTML (Pug), and JavaScript (TypeScript, CoffeeScript) due to the required build step. The combination of all of these languages and technologies into a single file may be one of the greatest features for component-based frameworks due to being able to congregate everything related to the component into a single file for better maintenance.

Limited Functionality for Greater Flexibility

Vue.js in and of itself is focused around rendering reactive and interactive user interfaces. It offers little in the way of structure or architecture. This is completely on purpose and it follows pretty much the same pattern as React in this regard. Like React, it lets other libraries handle the extra functionality, such as routing and more advanced, centralized state management. Unlike React, though, Vue.js provides officially supported libraries for some of these things, rather than leaving them up to third parties.

By removing this functionality from the core framework, you get a smaller file size and the flexibility to use other libraries if you want to. The trade-offs are that there are more choices to make and there isn’t necessarily 1 right way to do something because everyone is using something different. By officially supporting vuex and vue-router, though, these trade-offs are mitigated.

Conclusion

Everything is based off of something that already exists, and Vue.js is definitely no exception. Despite having nothing new, though, Vue.js’s growth and popularity most likely came about because it stole and combined many of the best concepts from the other frameworks out there and kept out many of the things that cause headaches for developers.

About the Author:

Elm: React Without Compromises

March 1st, 2017

The world of front end development has been experiencing a major paradigm shift over the past few years. Frameworks have shifted from Model/View and Object-Oriented paradigm of Backbone, Ember, Angularjs v1, and dozens of similar smaller projects to a new paradigm embracing immutable data structures, virtual DOM, and functional programming. The primary catalyst for this has been Facebook’s React framework powered by the large budgets Facebook poured into engineering and advocacy, and perhaps seizing the opportunity created by the delays and rewrites associated with Google’s AngularJS v2 framework.

React brings a hybrid ideology to the table combining virtual DOM and functional-style components (pass in state, get a rendered DOM result). But beyond that, React itself leaves a lot of paradigm and architectural questions open: state management, effect processing, mutability, etc. Thus some teams that want more functional programming concepts land on a stack of stateless React views, immutableJS data structures, and Redux for state change and application architecture. Within this stack, you are still ultimately coding in JavaScript and can use Flow for type annotations.

If those concepts click for you but you want something more coherent, have a look at Elm. Elm has been around (initially as a PhD Thesis) since 2012 and represents some of the core ideas adopted by React/Redux in a more thorough and integrated way by providing a new programming language that directly integrates these concepts.

With Elm, you get a strongly-typed functional programming language that compiles to JavaScript. An expressive type system allows the compiler to automatically detect many categories of errors such that they can never make it into a shipping Elm application. Elm has immutable data structures and pure functional semantics baked in. This is how it can offer a lot of guarantees about program correctness and also helps it achieve great virtual DOM performance. The strength of the type system enables large scale refactoring of your application without regressions.

So what constitutes an Elm application? First, there are no separate HTML templates and JavaScript code modules. The core library includes an Html module with a composable, functional API for representing a DOM tree. Each HTML element is a function taking a list of attributes and a list of children. These nest naturally so it ends up looking almost like HTML but with direct access to the power of a real programming language. That means your attribute values can be computed by a function, and lists of children can be processed with familiar functional programming list paradigms like map and filter. Ultimately your HTML is represented as a function that takes model data as input and returns the DOM structure as output. This model is composable, scales nicely, and deals well with complexity.

To build application behavior, Elm introduces the “Elm Architecture” where application actions such as clicking on a button, entering some text, or an AJAX response arriving are represented as strongly-typed events. These events (called Messages in Elm) are passed to a central update function whose job is to look at the current state, apply the logic appropriate for the current action message, and return a modified state for the application. This new state is then passed to the view function to render a new DOM tree, and virtual DOM can then efficiently update the real DOM.

This architecture has developers smiling as debugging and bug reproduction become much more consistent and tractable (although the type system prevents many bugs from shipping at all). One of Elm’s killer demos early on was the “time-traveling debugger” where you can navigate backward and forward in the history of application states and observe how the UI changes. This is made possible by the design tenets of the architecture.

Elm ships with a core set of libraries for both key language-level functionality for dealing with data structures as well as basic web application building blocks for HTML, HTTP, and JSON. On top of that, the community contributes packages that can be plugged into your application via the Elm-package tool.

The Elm community is much much smaller than the mainstream React community, and probably always will be. The main corporate sponsor of Elm, No Red Ink, is many orders of magnitude smaller than Facebook. However, there are many active collaboration points including Slack chat, Github, Facebook groups, twitter accounts, blogs, and books. There’s a detailed guide to the community resources below.

Elm is a great tool to sharpen your functional programming chops and it provides a much more pleasant and forgiving experience than other typed functional languages such as Haskell, largely due to Elm’s simpler types and extremely high-quality compiler error messages. At the moment, it is probably not mainstream enough for corporate projects in technology-conservative workplaces. However, it is in production use and can be great for side projects and as a learning tool. The techniques you learn and master in Elm can directly benefit how you write JavaScript in general and React/Redux as well.

Interested in learning more about Elm and exploring a bit? Here’s some key resources.

Essential Elm Resources

DevelopIntelligence Team Training Course on Elm

Elm Home Page has the primary docs

The Elm Guide is the official tutorial

Elm Slack Community has helpful channels especially #beginners

Planet Elm syndicates Elm-related articles and blog posts

Elm for Beginners video course at KnowThen

Elm articles on Medium

Elm FAQ is a community-maintained knowledge base

Elm in Action work-in-progress book by Elm luminary Richard Feldman

About the Author:

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

December 20th, 2016

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.

About the Author:

Comparing Angular 1 & Angular 2 Through Building a Pomodoro Timer

November 4th, 2016

Modern web development offers an incredible variety of tools, libraries, and frameworks to build web sites/applications. As of 2016, jQuery, React, Angular, and Vue are the most popular front-end libraries/frameworks in use. They can all be used to build and accomplish similar things, but in different ways. What are the advantages/disadvantages of each? How does each approach vary? What do the new tools of React, Vue, and Angular 2 offer that Angular 1, jQuery, and vanilla JS didn’t?

In part 1 of the series, we saw the similarities and differences between javascript and jQuery while building the same pomodoro app and we also discussed the advantages and disadvantages of each. In part 2 of the series, we will see how to use angular 1 and angular 2 to build the same pomodoro timer and we will discuss the difference in approaches taken by the two frameworks.

Explore Angular Courses

What is a pomodoro timer?

The pomodoro timer is an easy-to-use productivity method. Using this method, you work in 25 minute spurts with 5 minute breaks in between. Many people find it helpful for helping them focus and work on tasks during the day.

pomodoro timer

Project Overview

In this tutorial, first we will create a pomodoro timer using Angular 1. Then, we will re-create the same pomodoro timer using Angular 2.

Here is how the final version of pomodoro timer built using Angular 1 looks like :

See the Pen Pomodoro Timer : : Angular1.5 by Raj Gupta (@rajdgreat007) on CodePen.

Here is how the final version of pomodoro timer built using Angular 2 looks like :

See the Pen Pomodoro Timer : : Angular2 by Raj Gupta (@rajdgreat007) on CodePen.

Our pomodoro timer shows minutes, seconds, and gives simple control buttons. It’s a simple timer but can give enormous productivity gains if used right.

Building the Pomodoro Timer : Angular 1

Let’s first write the html code to create various elements of the pomodoro timer.

<div id="pomodoro-app">
<div id="container">
<div id="timer">
<div id="time">{{toDoubleDigit(minutes)}}
:
{{toDoubleDigit(seconds)}}</div>
<div id="filler"></div>
</div>
<div id="buttons"><button id="work">Work</button>
<button id="shortBreak">Short Break</button>
<button id="longBreak">Long Break</button>
<button id="stop">Stop</button></div>
</div>
</div>

Angular 1 has MVC(Model, View, Controller)/MVVM(Model, View, ViewModel) architecture. The model represents data (eg. javascript objects) of the application. The view is how we can display the data to user. Since Angular 1 supports two way data binding, any change in the model will automatically update the view and vice versa. The controller consists of the code that controls the interaction between model and view.

By setting ng-app=“pomodoroApp”, we are marking the corresponding div (with id pomodoro-app) as the root element of the Angular application. “pomodoroApp” is the name of the angular module that we will define later in javascript code. By setting ng-controller=“pomodoroController”, we are attaching a controller function (will be defined later) to the view. The controller function will consist of variables and functions needed for the view. ng-click defines the function (defined in controller) that will be executed when the corresponding button is being clicked. We will be using a background filler that will keep increasing as time progresses.

Let’s apply css to the above markup.

#container{
border:1px solid #333;
border-radius :20px;
width:400px;
margin:20px auto;
padding:20px;
text-align:center;
background : #333;
}

#timer{
color:#f00;
font-size:50px;
margin:10px auto;
border : 5px solid red;
border-radius:50%;
width:200px;
height:200px;
overflow:hidden;
position:relative;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor:default;
}

#time{
margin-top:70px;
z-index : 1;
position:relative;
}

/*
filler width is set to 200px (i.e. equal to width of the timer) so that it completely covers the timer in background. The height is initially set to 0px and it increases as timer progresses to give background fill effect.
*/

#filler{
background : #ddffcc;
height: 0px;
width: 200px;
position:absolute;
bottom:0;
}

#buttons button {
background:#4da6ff;
border:none;
color:#fff;
cursor:pointer;
padding:5px;
width:90px;
margin:10px auto;
font-size:14px;
height : 50px;
border-radius : 50px;
}

#buttons button#shortBreak{
background : #0c0;
}

#buttons button#longBreak{
background : #080;
}

#buttons button#stop{
background : #f00;
}

Now, let’s make the pomodoro app functional by adding the following javascript :

var app = angular.module("pomodoroApp", []);
/* Define a module named pomodoroApp*/

/* Defind the angular component*/
app.component('pomodoroComp', {
bindings: {},
templateUrl: '/componentGrid.html',
controller : ['$interval',function(interval){

var self = this;
self.started = false;
/* 
started variable stores the state of the timer. If it is true, it means that some task (work, short break, long break) is going on with pomodoro timer. If it is false, it means that the pomodoro is not yet started or it is stopped (by clicking stop button)
*/

self.minutes = 25;
/*
minutes variable stores current minute which is displayed in the pomodoro. 
*/

self.seconds = 0;
/*
seconds variable stores current second which is displayed in the pomodoro.
*/

self.fillerIncrement = 200/(self.minutes*60);
/*
fillerIncrement variable stores the value by which fillerHeight should increase.
*/

self.fillerHeight = 0; 
/*
fillerHeight variable stores the height of the background filler. Initially it is set to 0. As soon as a pomodoro task starts, its height starts increasing (by a value which is stored in fillerIncrement variable) and it keeps increasing till that particular task ends. On click of stop button, it is again set to 0.

*/


/*
resetVariables function will be called for each of the actions (work, Short Break, Long Break, Stop) to set the value of variables to values corresponding to that particular action
*/

self.resetVariables = function(mins, secs, started){
self.minutes = mins;
self.seconds = secs;
self.started = started;
self.fillerIncrement = 200/(self.minutes*60);
self.fillerHeight = 0;
}

/* handler to be called when user clicks ‘Work’ button */
self.startWork = function(){
self.resetVariables(25, 0, true);
};

/* handler to be called when user clicks ‘Short Break’ button */
self.startShortBreak = function(){
self.resetVariables(5, 0, true);
};

/* handler to be called when user clicks ‘Long Break’ button */
self.startLongBreak = function(){
self.resetVariables(15, 0, true);
};

/* handler to be called when user clicks ‘Stop’ button */
self.stopTimer = function(){
self.resetVariables(25, 0, false);
};

self.timerComplete = function(){
self.started = false;
};

/*
intervalCallback function is called each second, updates the values of minutes and seconds variables and reflect the updates in timer
*/
self.intervalCallback = function(){ 
if(!self.started) return false;
if(self.seconds == 0) {
if(self.minutes == 0) {
self.timerComplete();
return;
}
self.seconds = 59;
self.minutes--;
} else {
self.seconds--;
}

self.fillerHeight += self.fillerIncrement;
};

/* 
toDoubleDigit function converts a number to double digit. If num is single digit (0-9), it is prepended with a ‘0’ and resulting string is returned. If num is double digit, it is returned as such. This function is needed as we want to display ’05’ instead of ‘5’ in timer 
*/
self.toDoubleDigit = function(num){
return num < 10 ? '0' + parseInt(num,10) : num;
};


/*
Init method initializes the timer using $interval function such that a callback function (intervalCallback) is called after every second
*/

self.$onInit = function(){
self.interval = interval( self.intervalCallback, 1000);
/*
$onInit is automatically called when component is initialized. interval variable stores the reference id of the currently running interval. If we need to clear the interval, we will need this variable. Although in the demo, we are not clearing the interval, it’s always a good idea to clear the interval at some point.
*/


};

}]
});

Inside the view, we are using {{toDoubleDigit(minutes)}} to display current minutes in double digits. It is bound to $scope.minutes variable in controller. Thus, as soon as the value of $scope.minutes changes, the changed value is immediately reflected in the view. Same thing happens for seconds and filler height display.

Building the Pomodoro Timer : Angular 2

Now we’re going to build this exact same app using Angular 2.

Angular 2 uses the concept of components which could be considered as Angular 1 directives that are associated with their own template. Let’s go ahead and create the pomodoro app using Angular 2 component. For Angular 2, the angular team has chosen TypeScript over JavaScript. Typescript is a superset of JavaScript and created by Microsoft. So, we will be writing code in TypeScript for the pomodoro app.

html :

Loading…

Note : The following external javascript libraries are required to be added to the page (For the demo, they are already added in copepan settings):

https://npmcdn.com/core-js/client/shim.min.js
//cdnjs.cloudflare.com/ajax/libs/reflect-metadata/0.1.8/Reflect.min.js
//cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.37/system.js
//code.angularjs.org/2.0.0-beta.0/Rx.umd.js
//code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js
//code.angularjs.org/2.0.0-beta.0/angular2-all.umd.dev.js
**typescript :**

/* Import Component object from ng.core */
const {Component} = ng.core;

/* Import Bootstrap object from ng.platform.browser */
const {bootstrap} = ng.platform.browser;

/* Component decorator is used to add metadata to the typescript class*/
@Component({
/*
selector defines the name of the tag which is used to add the component on html page
*/
selector : 'pomodoro-app',

/*
styles defines the css associated with the component
*/
styles : [`
#container{
border:1px solid #333;
border-radius :20px;
width:400px;
margin:20px auto;
padding:20px;
text-align:center;
background : #333;
}

#timer{
color:#f00;
font-size:50px;
margin:10px auto;
border : 5px solid red;
border-radius:50%;
width:200px;
height:200px;
overflow:hidden;
position:relative;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor:default;
}

#time{
margin-top:70px;
z-index : 1;
position:relative;
}

#filler{
background : #ddffcc;
height: 0px;
width: 200px;
position:absolute;
bottom:0;
}

#buttons button {
background:#4da6ff;
border:none;
color:#fff;
cursor:pointer;
padding:5px;
width:90px;
margin:10px auto;
font-size:14px;
height : 50px;
border-radius : 50px;
}

#buttons button#shortBreak{
background : #0c0;
}

#buttons button#longBreak{
background : #080;
}

#buttons button#stop{
background : #f00;
}

`],

/*
template defines the markup associated with the component
*/
template : `

{{toDoubleDigit(minutes)}}
:
{{toDoubleDigit(seconds)}}
 
Work
Short Break
Long Break
Stop
`
})

class AppComponent{
/*
All the variables and functions below have same meaning as described in Angular 1 pomodoro code.
*/
constructor(){
this.started = false;
this.minutes = 25;
this.seconds = 0;
this.fillerIncrement = 200/(this.minutes*60);
this.fillerHeight = 0;
this.init();
}
resetVariables(mins, secs, started){
this.minutes = mins;
this.seconds = secs;
this.started = started;
this.fillerIncrement = 200/(this.minutes*60);
this.fillerHeight = 0;
}
startWork(){
this.resetVariables(25, 0, true);
};
startShortBreak(){
this.resetVariables(5, 0, true);
};
startLongBreak(){
this.resetVariables(15, 0, true);
};
stopTimer(){
this.resetVariables(25, 0, false);
};
timerComplete(){
this.started = false;
}
intervalCallback(){
if(!this.started) return false;
if(this.seconds == 0) {
if(this.minutes == 0) {
this.timerComplete();
return;
}
this.seconds = 59;
this.minutes--;
} else {
this.seconds--;
}
this.fillerHeight += this.fillerIncrement;
};
toDoubleDigit(num){
return num < 10 ? '0' + parseInt(num,10) : num;
};
init(){
self = this;
this.interval = setInterval( function(){
self.intervalCallback.apply(self);
}, 1000);
};
}

/* Bootstrapping the component */
bootstrap(AppComponent, []);

The Angular team has made a lot of changes in Angular 2. It would not be an anomaly to say that they completely revamped the framework and build it from scratch. The reason for doing so many changes was to remove the bad parts of Angular 1 and to take advantage of new features of ECMAScript6 (the new version of JavaScript). Let’s explore the most prominent changes made in Angular 2 and reason behind them.

Controller and scope are completely eliminated from Angular 2. Angular 2 is more focused towards Component based development and object orientation (because of typescript). Web applications nowadays have become too complex. Angular team chose to use web components in Angular 2 because other than providing encapsulation and reusability, web components manages the complexity of the application by providing isolation. Every component is independent of other components and can be used as such by simply importing it on a page. Each component has its own template and styles that will apply only to that particular component. It means that the css will not bleed out of the component. The same is not possible with Angular 1 as the CSS is applied on page level. We can even create custom elements with Angular 2 that could be reused as such or could be extended by other users.

As mentioned earlier, Angular 2 team has chosen typescript for writing code in Angular 2 . The choice is inspired from following facts :

  1. Typescript easily integrates with most of the already existing javascript libraries and existing javascript code. So, we need not worry about legacy code.
  2. Using typescript adds lot of advantages to the framework which includes optional static typing and support for object oriented features like inheritance and interfaces. Static typing allows the type checking during the compilation. An interface define a set of functionality as a contract. When the interface is implemented, all the members of the interface must be implemented. Traditional javascript support prototype-based inheritance which is not completely object oriented. Typescript supports object oriented class based inheritance which goes pretty well with other object oriented features.
  3. Typescript adds type support to javascript. It means that the bugs that are caused by false assumption of a variable being of certain type can be detected while compilation. The same is not possible with javascript as it is dynamically typed.
  4. Typescript is far better than core javascript in managing the complexity of large projects.

Angular 1 implements two-way data binding by dirty-checking method and use watchers to watch the model/view for changes. Higher number of data bindings means higher number of watchers and hence higher performance degradation. Angular 2 doesn’t come with built in two-way data binding, although even in Angular 2, we can create directives that support two-way data binding. Angular 2 primarily uses unidirectional tree based change detection which boosts performance. Although we are not using two way data binding in Angular 1 pomodoro app, its worth mentioning that it is considered to be one of the bad parts of Angular 1 and thus it is removed from Angular 2.

Explore Angular Courses

Because of the optimisations mentioned above, Angular 2 is considered to be 5 times faster as compared to Angular 1 (as per ng-conf [https://ti.to/ng-conf/2016/en]).

In Angular 1, the bootstrapping of the app could be done by using ng-app or by calling the bootstrap function. In Angular 2, it can only be done by calling the bootstrap method.

Angular 1 uses $interval which is Angular’s wrapper for window.setIntervalfunction. As specified in code, the callback function is executed after every 1000 ms. Intervals created by $interval service must be explicitly destroyed because they are not destroyed automatically after the controller scope is destroyed. $interval is not available in Angular 2, thus we can either use javascript’s setInterval orObservable.interval method of Angular 2.

Conclusion

We created two pomodoro apps, one using Angular 1 and other using Angular 2. The app built using Angular 2 carries the advantages of web components and shadow DOM and is also free from the performance degradation caused due to two-way data binding of Angular 1.

Bonus

Here is this pomodoro app done in React

See the Pen Pomodoro Timer : React by Raj Gupta (@rajdgreat007) on CodePen.

Here is this pomodoro app done in Vue

See the Pen Pomodoro Timer : : Vue by Raj Gupta (@rajdgreat007) on CodePen.

Explore Angular Courses

About the Author:

Style the Web More Effectively with SASS

October 12th, 2016

As the web grows and changes, new technologies arise to help the developers on their interesting journey in bringing life to ideas and designs. This is how CSS was initially born and how CSS preprocessing technologies such as SASS came into being. In this post we will explore some of what SASS has to offer. We will take a look at new useful functionalities and techniques which lead to more modular, reusable, and maintainable code. If this sounds good, let’s begin..

SASS stands for “Syntactically Awesome Style Sheets.” As the name states it adds additional syntax and also offers additional functionality.

Let’s explore what SASS has to offer with examples keeping in mind that this is simply an overview and that when you develop, you will need to make decisions as to when to apply which of the features listed.

Before we start, it’s good to mention that SASS initially had a different syntax, which did not resemble CSS. Imagine CSS without curly braces. In its recent versions, SCSS syntax was introduced which is now very much in line with the CSS syntax. So when you are seeing SCSS, it is SASS in its new syntax.

Variables

SASS adds the capability of defining and using variables within your stylesheet. There are 7 data types: numbers, strings, colors, booleans, nulls, lists and maps. For a more detailed overview please look at this here (https://sass-lang.com/documentation/file.SASS_REFERENCE.html#data_types) but for now this is a simple example:

screen-shot-2016-10-12-at-12-15-16-pm

Play with this gist on SassMeister.

As you can see $font-size, $line-height, and $h1-size are number variables and size for H1 is defined by setting it to the value of $h1-size. You can also have variables of other types as below:

screen-shot-2016-10-12-at-12-15-28-pm

Play with this gist on SassMeister.


So now defining and changing a theme of a site can be as simple as changing a few variables.

There are a few ways to implement Object Oriented Design Patterns using SASS such as Mixins, extends and nesting. As developers know, this leads to greater modularity and more reusable code.

Mixins

In its essence, a mixin is a form of a constructor, which combines a set of defined CSS properties and allows you to reuse it in other places. It can also be viewed as a function which sets certain properties, adds others and returns the result.

Example:

screen-shot-2016-10-12-at-3-22-50-pm

Custom FieldsPlay with this gist on SassMeister.

In the example above we are defining a square mixin and are using it in two places. Another way to use mixins is for cross browser properties:

screen-shot-2016-10-12-at-12-15-40-pm

screen-shot-2016-10-12-at-12-15-47-pm

Play with this gist on SassMeister.

Extends

This is also a way to implement OO design where a particular selector can inherit properties of another. Keep in mind that we are only defining and inheriting properties and if you are coming from the object-oriented world, this is a limited implementation. For example:

screen-shot-2016-10-12-at-12-15-56-pm

Play with this gist on SassMeister.

As you can see two different buttons “confirm” and “cancel” are defined in a way, where most properties are common and are defined only once in the final CSS.

Nesting

Nesting is a third way which allows sharing of properties between selectors. Here you are defining one selector inside another which can also define a selector inside it and so on:

screen-shot-2016-10-12-at-12-16-03-pm

Play with this gist on SassMeister.

Here the nesting is only two levels deep. When developers discover this feature, they are tempted to nest too many layers as it makes coding simpler for them. You do need to keep in mind of the way it will be rendered into CSS which can become complicated. Best practice for nesting is to keep it no deeper than 3 or 4 levels.

Additional functionality

There are many more features to explore but to go over them in detail will take too long. We will describe them below and you, the reader can explore them with your google muscles.. :)

Operations

Addition, subtraction, multiplication, division, modulus, equals and non-equals can all be done straight inside the CSS file.

Functions

There are two types of functions available in SASS.

    1. Pre-defined functions: SASS includes many functions for various things including string, color manipulations and math related methods like random() and round(). I would strongly recommend you explore these and use them as needed. You can find the full list here: https://sass-lang.com/documentation/Sass/Script/Functions.html
    2. Custom functions: You can also define your own functions to do what you would like:  https://sass-lang.com/documentation/file.SASS_REFERENCE.html#function_directives

 

Conditionals

@if, @else are conditional statements which allow you to add logic to your CSS and perform an action based on a condition. For more information check: https://sass-lang.com/documentation/file.SASS_REFERENCE.html#_9

Loops

There are also loops such as @for, @each and @while. These allow you to iterate through a list or a map and do some task as you would in other programming languages. For details check: https://sass-lang.com/documentation/file.SASS_REFERENCE.html#_10

Partials

Partials allow you to separate your CSS files into smaller files and organize them in a logical and easy to maintain way. For example:

screen-shot-2016-10-12-at-12-16-29-pm

Play with this gist on SassMeister.

screen-shot-2016-10-12-at-12-16-25-pm

Play with this gist on SassMeister.

(the last example with partial does not look good as it requires the partial file for imports. I would leave this one as an image)

Beyond SASS

Compass  compass is an extension of SASS which bring a number of additional features including cross-browser mixins and so on. (https://compass-style.org/) This is out of the scope of this article, but if you are thinking of using SASS you need to look into Compass as an addition and extension to SASS.

Compilation – We have to mention that SASS is a preprocessor for CSS and does need to be compiled into CSS before being ready to be sent to the browser. This adds an additional step in your site creation process. There are a number of tools that help you do this:

Sassmeister – For development you can use this convenient in-browser tool: https://www.sassmeister.com

Command line tools – You can also find Apps and command line tools here: https://sass-lang.com/install

Also let’s take a look at an example using maps which combines a few things together:

screen-shot-2016-10-12-at-12-16-38-pm

Play with this gist on SassMeister.

Note that here we are combining three things. First of all we are using maps, (i.e. key, value pairs). This is one of the data types at your disposal. Then we are using an @each loop to iterate through the map items and for each we are creating a corresponding class. Notice the special #{…} syntax. It allows for the value of a variable to be part of the name of the class – a very useful feature.

The CSS is above in the example.

To summarize, a preprocessor like SASS, brings additional flexibility and functionality, which can lead to cleaner and more manageable code in the long run. It can allow you to code in a more reusable and intuitive way. But for this you are adding an additional “CSS compilation” step to your build process. This being said, if you are working on a mid to large-scale project what SASS offer well outweighs the additional work.

In addition, the modular approach to CSS coding which SASS brings works really well with Front-End JavaScript frameworks like Angular.js, React.js, Ember.js, etc. so if your project uses any of the MV* JavaScript frameworks, you are better off using SASS.

About the Author:

Comparing Javascript & jQuery Through Building a Pomodoro Timer

October 11th, 2016

Modern web development offers an incredible variety of tools, libraries, and frameworks to build web sites/applications. As of 2016, jQuery, React, Angular, and Vue are the most popular front-end libraries/frameworks in use. They can all be used to build and accomplish similar things, but in different ways. What are the advantages/disadvantages of each? How does each approach vary? What do the new tools of React, Vue, and Angular 2 offer that Angular 1, JavaScript, and vanilla JS didn’t?

In this 3 part tutorial series, we’re going to build a simple pomodoro timer as a means to compare vanilla JavaScript, jQuery, React, Angular 1, Angular 2 and Vue.

What is a pomodoro timer?

The pomodoro timer is an easy-to-use productivity method. Using this method, you work in 25 minute spurts with 5 minute breaks in between. Many people find it helpful for helping them focus and work on tasks during the day.

screen-shot-2016-10-11-at-9-31-11-am

Project Overview

In this tutorial, first we will create a pomodoro timer using vanilla javascript. Then, we will re-create the same pomodoro timer using jQuery.

Here is how the final version of pomodoro timer built using vanilla javascript looks like :

See the Pen Pomodoro Timer : : Javascript by Raj Gupta (@rajdgreat007) on CodePen.


Here is how the final version of pomodoro timer built using jQuery looks like :

See the Pen Pomodoro Timer : : jQuery by Raj Gupta (@rajdgreat007) on CodePen.


Our pomodoro timer shows minutes, seconds, and gives simple control buttons. It’s a simple timer but can give enormous productivity gains if used right.

Building the Pomodoro Timer : Javascript

Let’s first write the html code to create various elements of the pomodoro timer.

<div id="pomodoro-app">

 <div id="container">

        <div id="timer">

        <div id="time">

    <span id="minutes">25</span>

    <span id="colon">:</span>

    <span id="seconds">00</span>

        </div>

        <div id="filler"></div>

        </div>

        <div id="buttons">

        <button id="work">Work</button>

        <button id="shortBreak">Short Break</button>

        <button id="longBreak">Long Break</button>

        <button id="stop">Stop</button>

</div>

 </div>

</div>

As you can see, nothing fancy here. Just a container with the timer and control buttons. We will be using a background filler that will keep increasing as time progresses.

Let’s apply some css to the above markup to make it look nice.

#container{

 border:1px solid #333;

 border-radius :20px;

 width:400px;

 margin:20px auto;

 padding:20px;

 text-align:center;

 background : #333;

}

#timer{

 color:#f00;

 font-size:50px;

 margin:10px auto;

 border : 5px solid red;

 border-radius:50%;

 width:200px;

 height:200px;

 overflow:hidden;

 position:relative;

 -webkit-user-select: none;

 -moz-user-select: none;

 -ms-user-select: none;

 user-select: none;

 cursor:default;

#time{

 margin-top:70px;

 z-index : 1;

 position:relative;

}

/*

filler width is set to 200px (i.e. equal to width of the timer) so that it completely covers the timer in background. The height is initially set to 0px and it increases as timer                   progresses to give background fill effect.

*/

#filler{

 background : #ddffcc;

 height: 0px;

 width: 200px;

 position:absolute;

 bottom:0;

}

#buttons button {

 background:#4da6ff;

 border:none;

 color:#fff;

 cursor:pointer;

 padding:5px;

 width:90px;

 margin:10px auto;

 font-size:14px;

 height : 50px;

 border-radius : 50px;

}

#buttons button#shortBreak{

 background : #0c0;

}

#buttons button#longBreak{

 background : #080;

}

#buttons button#stop{

 background : #f00;

}

Now the timer looks nice, but there is no functionality associated with it yet. Let’s add javascript to make it functional.

We will be using object oriented javascript in which all of the variables and functions of the pomodoro timer will be encapsulated inside an object. Below is the basic structure of the code :

var pomodoro = {

           ...………….

           …………….

           init: function() {

               }

           ……………

      …………….

};

//The pomodoro object consists of variables and methods in key value pairs.

window.onload = function() {

     
    pomodoro.init();

};

/* window.onload method is used to make sure that page and DOM are loaded before we call init method as it queries and manipulates DOM. */

Let’ s add variables and other methods which are needed to make the pomodoro timer work.

var pomodoro = {

           
    started: false,

    /*       
started variable stores the state of the timer. If it is true, it means that some task (work, short break, long break) is going on with pomodoro timer. If it is false, it means that the pomodoro is not yet started or it is stopped (by clicking stop button)
     
     */

           minutes: 0,

    /*

            minutes variable stores current minute which is displayed in the pomodoro.       

    */

           seconds: 0,

    /*

            seconds variable stores current second which is displayed in the pomodoro.

    */

           fillerHeight: 0,

    /*

            fillerHeight variable stores the height of the background filler. Initially it is set to 0. As soon as a pomodoro task starts, its height starts increasing (by a value which is stored in fillerIncrement variable) and it keeps increasing till that particular task ends. On click of stop button, it is again set to 0.

    */

           fillerIncrement: 0,

    /*

            fillerIncrement variable stores the value by which fillerHeight should increase.

    */

           interval: null,

    /*

            interval variable stores the reference id of the currently running interval. If we need to clear the interval, we will need this variable. Although in the demo, we are not clearing the interval, it’s always a good idea to clear the interval at some point.

    */

           minutesDom: null,

    /*

            minutesDom : It stores the reference of the minutes element of pomodoro. It’s good to store the reference so that it can be reused instead of querying the DOM again for the same element.

    */

           secondsDom: null,

    /*

            secondsDom variable stores the reference of the seconds element of pomodoro.

    */

           fillerDom: null,

    /*

            fillerDom variable stores the reference of the filler element of pomodoro.

    */

           init: function() {

        /*

                Init method initializes the variables and set event listeners for all buttons. It also starts the interval due to which a callback function (intervalCallback) is called after every 1 second and updates the DOM depending on the task which is in execution.

        */

               
        var self = this;

               
        this.minutesDom = document.querySelector('#minutes'); /* caching the reference to seconds dom object */

               
        this.secondsDom = document.querySelector('#seconds'); /* caching the reference to seconds dom object */

               
        this.fillerDom = document.queryS elector('#filler '); /* caching the reference to background filler dom object */

               
        this.interval = setInterval(function() {

                   
            self.intervalCallback.apply(self);

                   
        }, 1000);



                /* adding the listener to be called when user clicks 'Work’ button */

               
        document.querySelector('#work').onclick = function() {

               
            self.startWork.apply(self);

                   
        };

                /* adding the listener to be called when user clicks 'Short Break’ button */

         
        document.querySelector('#shortBreak').onclick = function() {

                   
            self.startShortBreak.apply(self);

                   
        };

                /* adding the listener to be called when user clicks 'Long Break’ button */

             
        document.querySelector('#longBreak').onclick = function() {

               
            self.startLongBreak.apply(self);

                   
        };

        /* adding the listener to be called when user clicks 'Stop’ button */

             
        document.querySelector('#stop').onclick = function() {

                   
            self.stopTimer.apply(self);

                   
        };

               
    },

    /* resetVariables will be called for each of the actions (work, Short Break, Long Break, Stop) to set the value of variables to the corresponding action values */

           resetVariables: function(mins, secs, started) {

               
        this.minutes = mins;

               
        this.seconds = secs;

               
        this.started = started;

             
        this.fillerIncrement = 200 / (this.minutes * 60);

             
        this.fillerHeight = 0;

               
    },

           startWork: function() {

         
        this.resetVariables(25, 0, true);

               
    },

           startShortBreak: function() {

               
        this.resetVariables(5, 0, true);

               
    },

           startLongBreak: function() {

             
        this.resetVariables(15, 0, true);

               
    },

           stopTimer: function() {

             
        this.resetVariables(25, 0, false);

             
        this.updateDom();

               
    },

           toDoubleDigit: function(num) {

        /*

        If num is single digit (0-9), it is prepended with a '0’ and resulting string is returned. If num is double digit, it is returned as such. This function is needed as we want to display ’05’ instead of '5’ in timer

        */

               
        if (num & lt; 10) {

               
            return "0" + parseInt(num, 10);

                   
        }

               
        return num;

               
    },



    /*

    updateDom function updates the values of minutes, seconds and filler height every second, so that user can see the remaining time and background fill height changing continuously

    */

           updateDom: function() {

             
        this.minutesDom.innerHTML = this.toDoubleDigit(this.minutes);

             
        this.secondsDom.innerHTML = this.toDoubleDigit(this.seconds);

             
        this.fillerHeight = this.fillerHeight + this.fillerIncrement;

             
        this.fillerDom.style.height = this.fillerHeight + 'px';

               
    },



    /*

    intervalCallback function is called each second, updates the value of minutes and seconds variables and calls updateDom function to reflect the updates in timer

    */

           intervalCallback: function() {

             
        if (!this.started) return false;

               
        if (this.seconds == 0) {

               
            if (this.minutes == 0) {

                         
                this.timerComplete();  /* As soon as both minutes and seconds variables become zero, it means that the timer is complete and it can be stopped now*/

                  
                return;

                   
            }

               
            this.seconds = 59;

                   
            this.minutes--;

                   
        } else {

                   
            this.seconds--;

                   
        }

             
        this.updateDom();

               
    },

           timerComplete: function() {

               
        this.started = false;

         
        this.fillerHeight = 0;

               
    }

};

window.onload = function() {

     
    pomodoro.init();

};

Building the  Pomodoro Timer : jQuery

Now we’re going to build this exact same app in jQuery. The HTML and CSS are exactly same as that of above.

var pomodoro = {

/*
All the variables and functions below have same meanings as described in javascript pomodoro code. The difference is only in how we will achieve the same functionality using jQuery code
*/

           
    started: false,

           minutes: 0,

           seconds: 0,

           fillerHeight: 0,

           fillerIncrement: 0,

           interval: null,

           minutesDom: null,

           secondsDom: null,

           fillerDom: null,

           init: function() {

               
        var self = this;

               
        this.minutesDom = $('#minutes');  /*  slower as compared to document.querySelector('#minutes’) */

               
        this.secondsDom = $('#seconds');

               
        this.fillerDom = $('#filler');

               
        this.interval = setInterval(function() {

                      
            self.intervalCallback.apply(self);

                   
        }, 1000);



        /*  adding the click handlers for work, short break, long break and stop buttons */

        $('#work').click(function() {

                   
            self.startWork.apply(self);

                   
        });

             
        $('#shortBreak').click(function() {

                   
            self.startShortBreak.apply(self);

                   
        });

               
        $('#longBreak').click(function() {

               
            self.startLongBreak.apply(self);

                   
        });

         
        $('#stop').click(function() {

               
            self.stopTimer.apply(self);

                   
        });

               
    },

           resetVariables: function(mins, secs, started) {

               
        this.minutes = mins;

               
        this.seconds = secs;

               
        this.started = started;

         
        this.fillerIncrement = 200 / (this.minutes * 60);

         
        this.fillerHeight = 0;

               
    },

           startWork: function() {

         
        this.resetVariables(25, 0, true);

               
    },

           startShortBreak: function() {

               
        this.resetVariables(5, 0, true);

               
    },

           startLongBreak: function() {

         
        this.resetVariables(15, 0, true);

               
    },

           stopTimer: function() {

         
        this.resetVariables(25, 0, false);

         
        this.updateDom();

               
    },

           toDoubleDigit: function(num) {

               
        if (num & lt; 10) {

               
            return "0" + parseInt(num, 10);

                   
        }

               
        return num;

               
    },

           updateDom: function() {

             
        this.minutesDom.text(this.toDoubleDigit(this.minutes));

             
        this.secondsDom.text(this.toDoubleDigit(this.seconds));

               
        this.fillerHeight = this.fillerHeight + this.fillerIncrement;

         
        this.fillerDom.css('height', this.fillerHeight + 'px');

               
    },

           intervalCallback: function() {

         
        if (!this.started) return false;

               
        if (this.seconds == 0) {

               
            if (this.minutes == 0) {

                    
                this.timerComplete();

                  
                return;

                   
            }

               
            this.seconds = 59;

               
            this.minutes--;

                   
        } else {

               
            this.seconds--;

                   
        }

         
        this.updateDom();

               
    },

           timerComplete: function() {

               
        this.started = false;

         
        this.fillerHeight = 0;

               
    }

};

$(document).ready(function() {

     
    pomodoro.init();

});

First of all, I would like to mention that jQuery is a huge library. In our pomodoro app, we have used a very small subset of the features that it offers. This is the biggest disadvantage of using jQuery for our case because we will be loading entire library and because of that, the page load time will be much higher as compared to javascript’s pomodoro app. In huge pages, using jQuery makes a lot of sense.

In the above code we are using $(‘#minutes’) for caching the minutes DOM element.  As a matter of fact, javascript’s document.querySelector(‘#minutes’) is way faster than jQuery’s $(‘#minutes’). This speed difference could not be realised in a small app (such as a pomodoro timer) but it is relevant for large pages where there is intensive DOM query. Javascript’s document.getElementById(‘minutes’) is even faster than document.querySelector(‘#minutes’). So, the speed of executions has the following order :

document.getElementById(‘minutes’)  > document.querySelector(‘#minutes’) > $(‘#minutes’)

The reason for the above speed difference being, under the hood $(‘#minutes’) boils down to document.getElementById(‘minutes’) wrapped by jQuery wrapper. But when we say $(‘#minutes’), jQuery has to a lot of work in identifying if the argument is a string, does it contain spaces, it starts with a ‘.’ or a ‘#’ or is it a tagname and so on. This extra work takes time and hence reduces the speed.

Although, jQuery is at disadvantage because its DOM query speed is less as compared to javascript but when it comes to code convenience, jQuery is far ahead of javascript.

In the pomodoro app created using javascript, we can easily spot long lines of code whereas in the app created using jquery, the code seems relatively short. That means, if we are using jQuery, we have to type less as compared to javascript to achieve the same functionality. Whereas in javascript there are different methods to query DOM (by id, class and tagname), in jQuery, one single selector takes care of all of them.

Moreover,  javascript’s document.querySelector(‘#work’) will not work in all the browsers. It may break in IE8. On the other hand, jQuery’s $(‘#work’) is guaranteed to work in all the browsers. The reason is, all jQuery’s methods are standardised to work across all browsers.

Additionally, jQuery provides support for chaining which means that we can chain a method call at the end of another method call and save few bytes by saving the amount of code required to be written if chaining was not supported. For example, we can do the following in jQuery :

$('#work’).css('background’,’#999’).show()

Here we have chained show() method at the end of css() method. On the other hand, javascript doesn’t support method chaining.

In jQuery, we are using $(document).ready(), to make sure that DOM is ready before we query it. In javascript, we used window.onload event to achieve the same. jQuery’s $(document).ready() event occurs earlier as compared to window.onload of javascript because the latter occurs after the DOM is loaded and all the resources (scripts, images etc) are also loaded.

Last but not the least, while writing javascript code, there is big scope for writing inefficient code. jQuery library on the other hand, is tested over time and highly optimised. Thus, if used carefully, the scope for writing inefficient code using jQery is very less as compared to javascript.

Conclusion

We created two pomodoro apps, one using vanilla javascript and other using jQuery. The two approaches are fairly similar, but jQuery offers an easier syntax in querying for elements and offers shorter (albeit slower) ways of doing things compared to JavaScript.

The differences between libraries/frameworks will get much more interesting in future posts, where we use Angular, React, and Vue to build this same app.

About the Author:

Building Nested Components using Angular 2

September 1st, 2016

Angular 2 consists of a lot of new features and one of the most fantastic features is the ability to create components. In fact Angular 2 is called a component-based framework and is directly inspired by web components.
Web components are the collections of standards that allow us to create reusable UI widgets. These widgets fully encapsulate all their markup and styles and could be easily imported on a page by simple one line import statement. Web components make the html language more expressive. Angular 2 components could be considered as Angular 1 directives that are associated with their own template, i.e.
Angular 2 Component = Angular 1 Directive +  Angular 1 Template

Project Overview

In this tutorial, we will create a very simple Angular 2 component (AppComponent or Parent component). Then we will create another component (Child Component) and we will see how to nest the child component inside the parent component.
After covering the basics of nesting one component inside another component, we will use this approach to create the application below where parent component consists of Author details and child component consists of his books. It’s a fairly simple demo app but should allow us to convey the concepts well.

See the Pen Angular2: Nested Components by Raj Gupta (@rajdgreat007) on CodePen.


Project Steps

  • Install and setup dependencies
  • Build Parent Component
  • Build Child Component
  • Nest Child Component

Project Setup

To create Angular 2 project, first we need to set up the environment and do few installations.

Install Node.js, npm and typescript

First we need to download and install node.js. It can be directly downloaded from node.js website. The downloaded package will install both node.js and npm (node package manager). We can check if the installations are successful by simply opening the terminal (cmd for windows) and writing the following commands:

node  -v

If node.js is installed successfully, the above command will output the version of the node.js. Similarly the below command will output the version of npm :

npm  -v

After node.js and npm are successfully installed, we need to install typescript. It can be easily installed by writing the following command in terminal :

sudo npm install -g typescript

The above command will install typescript with the following output :
It is recommended to write code in typescript and using a transpiler that converts typescript code into javascript code. One of the several reasons for using typescript language in Angular 2 is, typescript have in-build support for decorators/annotations which are helpful in creation of web component metadata.

Clone Angular 2 quickstart project from github

After installing node.js, npm and typescript, the next step is to clone Angular 2 quickstart project from angular github repository. This project provides the basic setup and we can start building our components on the top of it. To clone this project, open the terminal and type the following command :
git clone  https://github.com/angular/quickstart  angular-components
It will clone the angular quickstart project into a folder ‘angular-components’.
Next step is to navigate inside the ‘angular-components’ folder by typing the following command:
cd  angular-components
The next step is to install npm packages using the package.json file (included in ‘angular-components’ folder) by typing the following command:

npm install

It will install all the dependencies which are needed for the project including a transpiler to convert typescript files to javascript, a compiler that will keep looking for changes in project files and will recompile as soon as change is detected and lite-server.
Next, type the following command to run the application :

npm  start

This command will compile the application and run lite-server which has already been installed as project dependency. It will also open a new tab/window in web browser and we can see our application running on localhost on port 3000 ( https://localhost:3000 ).

Building the Parent Component

Now, the quickstart project is up and running and so we are all set to create our first component. Actually, the quickstart project already provides an example of a very simple component. If we go to https://localhost:3000, we can see the heading text “My First Angular 2 App”. That text is coming from a component that already exists in quickstart project and its called as AppComponent. We will understand all parts of the component step by step and modify it to create our parent component. The AppComponent exists inside a file called app.component.ts which is located inside ‘app’ folder. The ‘app’ folder is our working directory which consists of typescript (.ts) and javascript (.js) files. If we create a typescript file and write some code into it, it will be automatically transpiled to javascript file and will be saved inside ‘app’ folder.

//File : app/app.components.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }

Let’s understand each line step by step.
Step 1 : Import Component Object
import { Component } from ‘@angular/core’;
Angular 2 uses ES6 style syntax which allows to reuse code by importing them from one file to another.  In the above code, we are importing Component object from @angular/core. @angular/core is included as a dependency in package.json file and thus it was downloaded by npm when we executed npm install command.
Step 2 : Adding meta-data to class

@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})

We can add meta-data to our typescript class using the @Component decorator. The meta-data may include the following:
selector: It defines the name of the tag which can be used to add the component in html file. In the quickstart project example, the name of the tag is ‘my-app’ and we are going to use it as such. So, to use this component, we will use the tag <my-app></my-app> in the landing html file which exists in the angular-component folder and it’s called index.html.
styles: It defines the styles (css) associated with the component. It takes an array of inline styles. To specify external css file urls, we can use styleUrls instead of styles. We will use it while customizing the component.
template : It defines the markup associated with the component. It takes a single line or multiline string. We can specify multiline string in typescript by using backtick (`) character. We can also specify an external template by using templateUrl instead of template.
directives : If we want to use one component inside another (nested components), we can do so by specifying the child component in the directives attribute. It takes an array thus allowing us to nest multiple child components inside the parent.
providers :  We can pass the services which are needed by the component using providers.

Step 3 : Export the class

export class AppComponent { }
We need to export the class to make it usable by other parts of the code. After it is exported, it can be simply imported by using the import statement (as in step 1) and can be used. We can also specify variables and functions inside the class which can be used by the component’s template.
After understanding the bits and pieces of the above angular 2 component, we are all set to customize it as per our needs. We will use it as the parent component. We will change the template and will add few style that will be applicable to the component. Below is the modified version of the AppComonent.

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
         styles : [`
                     .parent {
                                 background : #c7c7c7;
                                 color : #000;
                                 padding: 20px;
                     }
         `],
template: `
                     <div class="parent">
                                 <h1>Parent Component</h1>
                     </div>
         `
})
export class AppComponent {}

Change 1 : Modified template

Added a div with class “parent” and changed the text inside h1 tag to “Parent Component”. We will soon see how to pass this data dynamically from the exported class and access it inside the template.

Change 2 : Added styles property

As mentioned earlier, styles takes an array. Here, we are passing a multiline string as the first element of the array. The multiline string consist of css that will be applied to the component markup specified by template property.
Now if we go to https://localhost:3000, we will see that the page is automatically refreshed and displaying the parent component markup with css specified through styles property applied correctly.
The data contained in h1 tag of the template is hard coded. We can make it dynamic by creating a variable in AppComponent class, assigning the data to that variable and accessing the data in template using double curly braces ({{ }}).

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
         styles : [`
                     .parent {
                                 background : #c7c7c7;
                                 color : #000;
                                 padding: 20px;
                     }
         `],
template: `
                     <div class="parent">
                                 <h1>{{name}}</h1>
                     </div>
         `
})
export class AppComponent {
         name = "Parent Component"
}

Building the Child Component

The next step is to create the child component. We will create a typescript file named ‘child.component.ts’ inside the ‘app’ folder and add the following code inside it:

//File : app/child.components.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-component',
         styles : [`
                     .child {
                                 background : #aaa;
                                 padding: 10px;
                     }
         `],
template: `
                     <div class="child">
                                 <h2>{{name}}</h2>
                     </div>
         `
})
export class ChildComponent {
         name = "Child Component"
}

The name of the selector is ‘child-component’, which means it can be inserted by using the  tag <child-component></child-component>. It has its own styles and template. There is also a name variable inside the ChildComponent class which is being used inside the template, just like we did for the AppComponent.

Nesting the Child Component Inside Parent Component

At this point, we are done with creating both the components. Now, the final step is to nest the child component inside the parent component. We need to make the following 3 changes inside the app.component.ts file to achieve this :
Step 1 : Import child component
To use a component, first we need to import it. It can be easily done by one line import statement:

import { ChildComponent } from './child.component';

Here, ChildComponent is the name of the class that we exported from child.component.ts file.
‘./child.component’ specifies the path of the component. We do not need to use the extension (.ts) while writing import statement.
Step 2 : Add the imported component inside the directives property of AppComponent decorator
As mentioned earlier, directives property specifies any child component which we want to use inside the parent component. In the component decorator of AppComponent, we will add the directives property and assign imported child component to it :
directives : [ChildComponent]
Step 3 : Use the Child component tag inside parent component template
The modified parent component template would look like:

<div class="parent">
<h1>{{name}}</h1>
<child-component></child-component>
</div>

With the above 3 changes in place, the final version of app.component.ts file will be :

import { Component } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'my-app',
         styles : [`
                     .parent {
                                 background : #c7c7c7;
                                 padding: 20px;
                     }
         `],
template: `
                     <div class="parent">
                                 <h1>{{name}}</h1>
                                 <child-component></child-component>
                     </div>
         `,
         directives : [ChildComponent]
})
export class AppComponent {
         name = "Parent Component"
}

Now, we can navigate to https://localhost:3000 and see the child component nested inside parent component.
Now we are all set to use the above setup to create an Author (Parent Component) and nest his books (Child Component) inside Author.
Let’s open app.component.ts and change it as follows (changes are marked in bold) :

import { Component } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
   selector: 'my-app',
  styles : [`
.parent {
    background : #c7c7c7;
    padding: 20px;
}
  `],
   template: `
<div class="parent">
    <h1>Author : {{name}}</h1>
       <child-component></child-component>
</div>
  `,
directives : [ChildComponent]
})
export class AppComponent {
name = "John Doe"
}

Here we tweaked the template to display Author name and also changed it from inside the class.
Now let’s open child.component.ts and change it as follows (changes are marked in bold) :

import { Component } from '@angular/core';
@Component({
   selector: 'child-component',
   styles : [`
.child {
    background : #aaa;
    padding: 10px;
    overflow:auto;
}
.book{
    background : #0a0;
    padding:20px;
    margin:10px;
    width:300px;
    float:left;
}
   `],
   template: `
<div class="child">
<h2>Books :</h2>
<div class="book" *ngFor="#book of books">
<h4> Title : {{book.title}} </h4> <h4>Price: {{book.price}}</h4>
</div>
</div>
   `
   })
export class ChildComponent {
books = [
   {
title : 'Love Story',
price : 'Rs. 1400'
   },
   {
title : 'Two States',
price : 'Rs. 1700'
   },
   {
title : 'Computer fundamentals',
price : 'Rs. 1000'
   }
 ]
}

Here, we have assigned the array of books to a variable named books in the ChildComponent class. We also changed the template to add books markup. We are using *ngFor (equivalent to ng-repeat of Angular 1) to loop through the array of books and displaying title and price of each book.  We also added css for styling each of the book.

Conclusion

We went through the details of Angular 2 components and use of typescript language to create them. We also went through the attributes of component decorator (selector, styles, template, directives, providers) which are helpful while creating the component. We saw how to create components and finally how to nest child component inside a parent component.

About the Author:

Handling the Challenge of Shared State With Ngrx/Store in Angular 2

August 25th, 2016

The state we’re in:

Angular2 has gone a long way in making UI apps more modular. The app has become a tree of potentially independent components that can be tested in isolation. Http operations are encapsulated in their own class and use Observables for asynchronous operation. The Forms have been overhauled with built in controls and validators. All in all things are much more modular and reactive. The problem of shared state remains, however.

As client-side apps become more complex, the need to handle more and more state on within the browser increases. As components need to share data between them we end up with bits and pieces of the state stored and managed all over the app, often with dependencies on the state managed by other components and our nice, componentized, highly testable, modular app is suddenly tightly coupled again. It’s also difficult to get a picture of the total state of the app.

Explore Angular Courses

Enter Redux

An increasingly popular pattern for dealing with this problem is Redux. The basic principles of Redux are as follows:

  • All the state in the app in encapsulated in a single JavaScript object called state, which is held in a store.
  • The store is immutable and never directly changed.
  • User interaction, events etc. fire actions which describe what has happened and encapsulate the data.
  • A function called a reducer combines the old state and the action to create the new version of the state, which is stored in the store.

Using this style makes the complicated job of state management more predictable, it separates the functional code from the presentational (separation of concerns) and the app code easier to maintain.

It’s possible to use Redux directly in Angular2, however that is more work than using a library implementation. There are a couple of implementations available and this post will use one of them, ngrx-store

Example app

The Angular2 seed project can be used to generate starter projects based on Angular2. Out of the box it presents a list of scientists along with an input box to allow you to add your own:

The initial list of names comes from doing an http call to get a list from a local file, data.json, which is in the assets folder. The service code that initiates this is the NameListService which is found in the shared/name-list folder:

In this tutorial we will update the app to use redux via ngrx-store and hook it into the service.

Pre-requisites, etc.

The examples below assume you are following the standard set-up and conventions of using Node & NPM, typescript for development and Angular 2 as per the seed project.  Details of how to get up and running are in the seed project ReadMe file.

Step 1: Add ngrx-store as a dependency

We need to add ngrx-store to the project package.json file. These are highlighted below:

"dependencies": {

 "@angular/common": "2.0.0-rc.5",

 "@angular/compiler": "2.0.0-rc.5",

 "@angular/core": "2.0.0-rc.5",

 "@angular/forms": "0.3.0",

 "@angular/http": "2.0.0-rc.5",

 "@angular/platform-browser": "2.0.0-rc.5",

 "@angular/platform-browser-dynamic": "2.0.0-rc.5",

 "@angular/router": "3.0.0-rc.1",

 "es6-module-loader": "^0.17.8",

 "core-js": "^2.4.0",

 "@ngrx/core": "^1.0.0",

 "@ngrx/store": "^2.0.0",

 "rxjs": "5.0.0-beta.6",

 "systemjs": "0.19.27",

 "zone.js": "^0.6.12"

}

 

After this we need to run NPM install to bring in the requisite node modules.

Step 2: Introducing the key concepts of Redux

Any ngrx-store (and Redux) app relies on the following key components

  • Store
  • Reducers
  • Actions

Store

The Store is the Javascript object that holds the application state. The common analogy is that it is like a database. The state maintained by the application is an array of strings which hold the names of the famous scientists. This is therefore what we will maintain in our store.

With ngrx-store, the convention is to create the store at bootstrap time. Until the recent (at time of writing) addition of modules to Angular2 this was achieved by importing the provideStore function and using it on bootstrap of the app. Now, we need to import the StoreModule from ngrx-store to the root module of the app and call provideStore on that. In the case of the seed application, the root module is defined in app.module.ts.

First we add an import to import StoreModule from @ngrx/store. Then in the imports serction of the NgModule declaration, we add the code which instantiates the Store:

StoreModule.provideStore( {names})

import {StoreModule} from '@ngrx/store';

import { names } from './shared/store/name-reducer';

@NgModule({

 imports: [BrowserModule, HttpModule, RouterModule.forRoot(routes), AboutModule, HomeModule, SharedModule.forRoot(),

   StoreModule.provideStore( {names})],

 declarations: [AppComponent],

 providers: [{

provide: APP_BASE_HREF,

useValue: '<%= APP_BASE %>'

 }],

 bootstrap: [AppComponent]

Wait! What is that parameter, “names”? That is a reducer, and they are covered in the next section. A more complex example will contain many reducers but as this in an introduction we’ll keep it simple.

Now we have set up the store, we need to make it available to all the sub-components that make up the app. The next change we do is to the AppComponent, defined in app.component.ts

This time we add the import statement for the Store:

import {Store} from '@ngrx/store';

And then change the constructor from this:

constructor() {

 console.log('Environment config', Config);

}

To this:

constructor(private _store: Store<any>) {

 console.log('Environment config', Config);

}

You can see where the store will be injected into the new private attribute, _store, and then be available to the rest of the components in the app.

Reducers

The usual analogy is that if the Store is the database, the reducers are like the tables in the database. They represent the “slices” of state that we want to keep track of. What makes this harder to grasp is that they may not represent a single recognisable business object. They could just be the state of a UI component, but for now we’ll keep things simple.

When dealing with Reducers, some theory needs to come in. Reducers need to be pure functions. A pure JavaScript function:

  1.       Always evaluates to the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices (or HTTP calls).
  2.       Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices or HTTP calls.

In our example app, we’re going to add a reducer function, names. In a new file, src/client/app/shared/store/name-reducer.ts, we add the following:

export const names = (state = [], action) => {

let index: number;

switch (action.type) {

    case 'ADD_NAME_LIST':

        return action.payload;

    case 'ADD_NAME':

        return [...state, action.payload];

    default:

        return state;

}

};

So what’s going on here? Well we’re declaring a function that takes two parameters: the state and and action. In this example state is initialised to be an empty array. The Store will use this function to determine how the state will be changed. If the type of the action is ‘ADD_NAME_LIST’ then the function will return the payload associated with the action (in this case it will be the list of names returned by the NameListService). If the action type is ‘ADD_NAME’, then the payload (in this case a new name string) will be appended to the existing state. Lets take a look at actions.

Explore Angular Courses

Actions

While the Store stores the state, and Reducers output how the state changes, Actions are what communicate to the Reducers when the state needs updated. In an application that uses ngrx-store, all user interaction that would cause a state update has to be expressed in the form of actions. Actions are simple JavaScript objects that implement this interface:

export interface Action {

 type: string;

 payload?: any;

}

The type is a string, denoting what change in state has occurred. The payload is a JavaScript object containing any data that is associated with that state change.

When a triggering event occurs, the relevant action is dispatched to the store which then triggers the relevant reducer function, resulting in a new version of the state. Which we will see in a moment.

Changing the Service

The next changes are to the NameListService. Like the app component, we add a _store attribute to the constructor so that the Store can be injected into the service. Thus this:

constructor(private http: Http) {}

Becomes this:

constructor(private http: Http , private _store: Store<string[]>) {

The original code had a “get” method that loads the JSON data file, returning an Observable array of strings. I have added a new function that instead will load the JSON data file, then dispatch the ‘ADD_NAME_LIST’ action to the store so the loaded list of names (which goes into the payload of the action) go into the store instead. This is the new function:

getnamesNgrx() {

 this.http.get('/assets/data.json')

  .map((res: Response) => res.json())

  .map(payload => ({ type: 'ADD_NAME_LIST', payload: payload }))

  .subscribe(action => this._store.dispatch(action));

}

As you can see, the payload in the response from the http call is mapped to the payload of an action object of type’ADD_NAME_LIST’.

The action is then dispatched to the Store, which will call the Reducer function outlined above, and move the payload (the list of names) into the store.)

Changing the home Component

Finally, we change the HomeComponent, which is defined in home.compent.ts. Yet again we add a Store attribute to the constructor so it can be injected. This:

constructor(public nameListService: NameListService) {}

becomes this:

constructor(public nameListService: NameListService, private _store: Store<any>) {

In the original version, the HomeComponent calls the get() method on the NameListService on the NgInit method. We now replace that with a call in the constructor to the new getnameNgrx()method on the NameListService instead.

this.nameListService.getnamesNgrx();

this._store.select('names')

.subscribe(names=>{

this.names = names;

 });

Next, we call select on the store and bind the local variable, names to the list of names in the store. Because the store is an Observable, this means that every time the list of names in the store is updated, our local variable which is subscribed to it (which is bound to the display on the UI page) will change too.

The last change is to the code that adds the name to the list. The original version pushed the new name onto the array of names. We change that to – you guessed it – dispatch an action of type ‘ADD_NAME’  to the store instead (Note: The TODO is from the original code!):

addName(): boolean {

 // TODO: implement nameListService.post

 // this.names.push(this.newName);

 this._store.dispatch(<Action>{type: 'ADD_NAME', payload: this.newName});

 this.newName = '';

 return false;

}

The Store fires the reducer function outlined above and the new name is added to the list in the store. Because the local variable, names, in the HomeComponent is subscribed to the names in the Store, it will be updated as well.

And that’s it. We’ve now converted the seed application to use Redux with ngrx-store instead.

Summary

Yeah but that’s really simple, I hear you say. Indeed it is and a real world application will be a lot more complex. There are a lot of other topics to get into, like Reducer Composition, Rehydration of the Store and others, however hopefully this has served and a useful introduction to Redux and Ngrx-store.

Further reading/watching:

Explore Angular Courses

About the Author:

Teaching JavaScript for a Living: Lessons Learned Through Teaching Thousands of Developers

July 20th, 2016

ericwgreene

Eric Greene is a full-stack developer and appendTo/DevelopIntelligence instructor. Over the past 5 years, Eric has taught JavaScript and front-end development to several thousand developers at dozens of Fortune 500 companies. In the last 2-3 years, Eric has taught several hundred Angular and React courses.

We interviewed Eric to find out what he has learned about teaching front-end development for a living.

Outline

  • Teaching JavaScript first
  • Thoughts on teaching Angular
  • Angular 1 vs. 2
  • Teaching React
  • Where JavaScript is going
  • Let the programmers program

appendTo/DI:

Hi Eric, what’s it been like to teach JavaScript, and especially Angular, for a living? What are the joys? What are the frustrations?

Eric:

Happy to talk! But before I can talk about teaching Angular… the first comment I’m going to have actually has to do with teaching any of the JavaScript libraries or frameworks. Be it Angular and React and Backbone and Marionette and any other JavaScript framework or library you want to cover. The single number one biggest problem with teaching any of those is that most of the students don’t really know JavaScript. So, when you go to teach those classes, you’re not just teaching a framework or a library. You’re also teaching the entire language, or almost the entire language, that those libraries and frameworks are coded in. And that is really the number one biggest, most frustrating challenge.

It would be like teaching a Java class, for example, on Spring MVC. But you show up to class and nobody knows Java. This happens over and over and over again. It doesn’t matter who the training customer is. This is universal across the board.

The reason why I believe it’s such a big problem is that most people don’t have a proper respect for JavaScript. The problem that you run into is that when you start writing Angular, React, Backbone type applications, you quickly start to realize that JavaScript is a real language that has a lot of principles, concepts, ideas that go into it. When you actually start building applications that are 90% JavaScript code, you really start to leverage those ideas and principles. Not only do people not understand what they are, they don’t even know that they exist.

What happens is developers come into a front-end web development class that’s JavaScript-heavy and they think they’re just going to jump right into the framework or the library and they can’t because they don’t even understand the language it’s actually written in. That problem is further compounded, especially with React and Angular 2, because those languages make heavy use of ES2015. They make heavy use of other domain-specific languages or other sub-languages, like a TypeScript or a JSX that are basically further additions and enhancements to ES2015.

You basically come into a class with a bunch of people who barely know ES5. No concept of ES2015. No concept of these other languages such as JSX. They expect to hit the ground running writing code with relative efficiency and ease right from the start. They quickly realize that there’s this entire ecosystem of programming they don’t even know exists. They really have no idea of the knowledge they don’t have. They don’t know what they don’t know.

appendTo/DevelopIntelligence:

That makes sense. Trying to learn the libraries/frameworks without really understanding the underlying language. What would you say are some other challenges?

Eric:

The next part that’s really challenging, and this is more so true of Angular than it is of React, is that the APIs for the frameworks are really large. And the tooling doesn’t always give the best code completion or intellisense. JavaScript, itself, has a lot of the syntax which is kind of hard for people. Combine that with something like an Angular that doesn’t always give the best error messages, and you have a real challenge on your hands. There’s something called the injector error, which is basically a syntax error in your JavaScript nine times out of ten. But the problem is it doesn’t tell you where. You have to hunt through all of your JavaScript source code that you modified since the last time it ran successfully. The whole debugging process of that can be very challenging for students. That’s probably the second biggest frustration when it comes to Angular 1. It’s the JavaScript typos, the large API, and the error messages that are really hard to debug.

appendTo/DevelopIntelligence:

What specifically about the large API catches people or is really hard for people to get at first?

Eric:

Really it’s the tying of all of the pieces together. What’s a directive? When is it used? What’s a service? What’s a controller? What’s a scope? How do scope objects get bound to a template? How do forms work? When I set up something on a scope in one controller, how does that impact other scope objects? Child scope objects? Parent scope objects? Of course, all of those things are built around the concepts of prototype inheritance. If they don’t understand prototype inheritance, then they’re not going to understand the scope object hierarchy. If they don’t understand the scope object hierarchy, then they have a really hard time trying to build an application of any real size. Depending upon the chosen development tooling, there’s no real intellisense or code completion. For many developers, they’re basically back to just using a simple text editor. Although, this is getting better with tools such as Visual Studio Code and Atom. Editing all of this code in a simple editor and working with a brand new language and a huge framework can make for a challenging learning experience.

appendTo/DevelopIntelligence:

Interesting. What have you found helps people understand? What kinds of tricks do you use? I’m sure through teaching so many people, you’ve probably found quite a few little shortcuts to hacking people’s understanding of these.

Eric:

The biggest thing I do to help developers is that I write actual code from scratch, live. And I get my students to write code as soon as possible in the course.

It really doesn’t work to sit people down and go through endless PowerPoint slides and then bore them with highly scripted labs where it’s basically go to line 33, type in a line of code, and watch it run. Labs where students modify one function in the middle of some file without really having proper appreciation of the larger context doesn’t work at all. Sure, they feel good about themselves when it runs, but they haven’t learned anything. I have been told by so many clients about training classes where students sit through endless slides, prepared code demos and scripted labs, then get to the end of the training and are unable to actually code an application.

For people to learn, they really have to code something from the ground up where they actually create every aspect of the application. Let’s say I only had one day to teach Angular. What would I do in that one day? I would have them build a simple CRUD application that incorporates all of the major components of Angular and demonstrates how they work individually, how they work together, why they do what they do, and at the end they actually produce something that’s actually functional.

appendTo/DevelopIntelligence:

Yeah. Makes sense.

Eric:

And they will code the whole thing from scratch. There’s no pre-filled out file. No just going in and writing this one function. Because what happens is that people, instead of really digesting and understanding all the pre-written code, they just focus in on how quickly can they get the lab done. How quickly can I write that one function? And if you said “Okay, well now that you wrote that one function, now go back and build me a larger application,” they’re incapable of doing it.

Whereas if you actually have them build the application…there’ll be parts of the application that require more help and assistance than other parts. Maybe they wouldn’t be able to really completely rebuild the whole thing from scratch from memory. But, their ability to actually take what they have coded and then go use it somewhere is greatly increased because they actually wrote an application. That’s been my approach.

The other things I do to help people understand is that I believe strongly in doing public presentation of student code. I use group debugging sessions. When a student really isn’t getting it or they don’t understand it or their code is broken and they can’t figure out how to fix it, we have them plug their computer up and the students, the class as a whole, help to debug the application with them. Usually I step back as an instructor and sit in the back of the class and watch them. Then, if they get collectively stuck, then I’ll jump in and give them a little bit of information to keep moving them forward. But the key to doing that is you have to have an instructor who really loves to write code, knows how to debug code, actually understands how the technologies work, and is willing to jump in there and risk having something not work or break.

appendTo/DevelopIntelligence:

How would you contrast both learning Angular 2 versus Angular 1 for yourself? And how would you contrast teaching the difference between the two?

Eric:

When I first learned Angular 2, I knew what to look for. I knew the problem it was trying to solve and I just had to memorize the APIs to use it. The way you memorize the APIs is to write lots of code with it as fast as possible. If you write lots of code, solving the problems over and over again, you remember the APIs.

What’s the difference? The first thing you have to realize is that Angular 1, Angular 2, React, Ember, Backbone, Marionette, Dojo, is that they all actually solve the same problem. They’re all different ways of solving it. But at the end of the day, they solve the problem how do I build a UI in a web browser without having to reload the page? How do I build single-page apps?

The key is once you understand the various problems that have to be solved by the libraries and frameworks, then when you encounter a new library or framework, you just go figure out how that library or framework solves that particular problem.

appendTo/DevelopIntelligence:

What’s your opinion on how different libraries/frameworks solve the problem?

Eric:

It depends. Take Angular 1. Angular 1 is a much more we’ll say free-form, open-ended framework. Basically, you have this concept of directives. A directive can have a controller. It can have a template. Or you skip the directive and just have a controller and then that controller’s applied on a template somewhere. You can configure the scope object how you want. Set up your template variables, whatever. You have a lot of control.

In Angular 2, what they did is they incorporated the new popular pattern of web component-driven development. They took the concept of a directive that has a template and a controller and put it into a special kind of directive called a component. Now when we do Angular 2 development, instead of having a general purpose API, they now give you more specific APIs to work with. Less flexibility, but better application design and organization.

appendTo/DevelopIntelligence:

Can you share any specifics of where you think it got easier or harder?

Eric:

It’s easier in the sense of working with a component. Identifying a special kind of directive that’s called a component that’s basically a controller combined with a template and then provided a very specialized component called a component. But a specialized thing makes it much easier to work with because people can identify that specialized thing. But, it makes it a little harder because the more specialized things that you have, the more unique little APIs you have to memorize. But if you think about it like this, JavaScript, the built-in DOM functionality in a web browser is probably the most free-form, easy way to go about building anything. You have the most freedom. But the result of that is that you have to come up with all the conceptual ideas yourself.

Whereas, when you move to a library, the library solves certain problems for you. But, you still have to do the overall conceptual idea of ‘how do I put all the different libraries together to actually then build a framework for my solution?’ When you go with a framework, it’s much more controlling and specific about how to do things. But, specific and controlling is relative. Angular 1 is much more free-form, less specific, less controlling. Angular 2 has more patterns that are baked into it, like component-driven development. You can do component-driven development in Angular 1, but you don’t have to. In Angular 2, you don’t have a choice.  With all that said, Angular 1.5 now has a new component API built into it showing the importance of the web component pattern.

appendTo/DevelopIntelligence:

How is it teaching Angular 2 so far? How do students take to Angular 1 vs. Angular 2?

Eric:

I find that covering the same material in Angular 2 takes longer than Angular 1. I’m not really sure why. I think part of it has to do that in Angular 2, everything is in ES2015 (well, TypeScript actually). So, in addition to learning “normal” JavaScript, now they’re learning TypeScript. This requires more time to cover all the strong typing and everything else that goes along with it. Also, because of the component-driven pattern, you spend more time talking about component-driven design. I call it composing components. Taking multiple components and putting them together to build larger components. This composing process proves to be challenging for many students. But that’s something that I didn’t spend a whole lot of time on in Angular 1 classes because I didn’t force them to go down a specific pattern path. Instead, I taught them how the Angular 1 API works, all the ins and outs and details of it, but didn’t say ‘oh you have to do a component-driven pattern’.

appendTo/DevelopIntelligence:

Let’s talk about React a little bit. What’s your thoughts on it? What’s it like teaching on it? How are people learning it?

Eric:

I think React is great. It’s a great little library. It’s great for building components. It’s a little bit different way of looking at the world. So that can be a little challenging for students.

appendTo/DevelopIntelligence:

How so?

Eric:

In terms of understanding the flow of data and understanding that everything is uni-directional in nature. The DOM never directly updates the underlying model and user interactions never directly update the DOM. Instead, the DOM fires events and the events are handled by React to update the underlying model and then update the DOM again with the result of the changes. Consider the process of typing into an input field. Instead of taking the value typed in and updating the model or DOM, that value is passed through an event, which then gets passed back into the component. Then the component handles it. It’s the one way data flow that people are not used to (especially when they come from two way data-binding frameworks).

Because of this, it becomes a little bit more challenging for them to understand the flow of data in React. But on the whole, React itself is actually pretty easy to teach once people understand ES2015, which is the only way I teach React. The reason we only do ES2015 is that you have to use a transpiler for JSX anyway. So, if you’re going to use a transpiler for JSX, you might as well transpile the ES2015 code too. Why intentionally write your code in an old language?

We basically build a CRUD application, but it takes longer to teach then Angular 1. So, the same CRUD application that I can build in a half a day in an Angular 1 class, takes us all day in a React class. Because it is only a library and because of the way the data moves, it requires a little bit more work to accomplish the same thing.

appendTo/DevelopIntelligence:

Explain that process. What do you have to cover with React in a longer amount of time than what Angular allows you to do in half the time?

Eric:

It just takes longer. With Angular, because of the whole template two-way data binding and automatically hooking up of the data from the model to the view, it just all works right out of the box. In React, you have to wire up a lot more stuff. Wiring all that stuff up just takes longer to accomplish.

You’ve got to look at it from this perspective. Angular is a far larger topic. So with React, once you have your component working, you’re done. You’ve covered React. With Angular, once you have a component working, that’s great. But there’s so much more to it. There’s filters or what are known as pipes. You have services. You have a bunch of complex unit testing stuff and React has some of that too. But there’s more to an Angular application than there is to React in terms of the library versus the framework. But when strictly building the Hello World CRUD application, more work is required for React than it does in Angular.

appendTo/DevelopIntelligence:

What do you think are the advantages of React or advantages of Angular over React?

Eric:

React and Angular 2 have the advantage of following this whole component-based development paradigm. I would not choose Angular 1 to build any new applications whatsoever. Even though you can take a component-based approach with it, I think that having a framework or a library that has the component-based pattern already baked into it is far better.

I like Angular 2 a lot. I think it’s really cool and I think it’s going to be super successful. I think it’s going to be a learning curve for people because it’s not just a new framework. They have to learn new languages and new tooling and everything else.

appendTo/DevelopIntelligence:

If you were to teach a class where you had to build maybe more of a medium-sized app, something that’s a little bit more complex or interesting than Hello World, would React and Angular take more or less time? What does this look like beyond Hello World?

Eric:

Angular, to do that, takes about a week with Angular. Really it takes a little longer than that. I have yet to teach an Angular 2 class where we were actually able to complete the medium-sized app within the week. Because there’s so many moving parts and pieces to it all, as well as, many new ideas and concepts that students have to learn.

There’s a bunch of subtopics that are emerging out of the React and Angular 2 worlds. Things like immutable programming and reactive programming. These topics in and of themselves are huge. How you leverage them within these frameworks and libraries is actually a really important thing to consider, discuss and talk about in a class. To really build a full-blown, medium-sized application and really leverage the lot of these new ideas, you probably are looking at longer than a week to do that in Angular.

On the React side, it’s a little different because React only does the component part. So, you have to answer a bunch of additional questions about what pattern do you want to use for architecture in the overall application, be it Flux, Redux, or MVC. How do you want to utilize React as part of a larger application? That’s a little bit harder to answer.

appendTo/DevelopIntelligence:

What are your general thoughts on where the JavaScript ecosystem is going and what works and what doesn’t and how it’s evolving?

Eric:

Well, I think the component-based approach is the way to go in terms of building a bunch of UI stuff. Any framework or library you’re going to use from a pattern standpoint and from a technology standpoint should be embracing the whole concept of components and everything that entails. That’s number one. Number two, in terms of the JavaScript language and tooling itself, I see transpilers becoming very important and very big. Basically, JavaScript will continue to advance and improve but the browsers will take a while to catch up. So transpilers will become more important and commonly used.

I see languages like JSX and TypeScript and CoffeeScript becoming the norms, not the exception. You’ll still do JavaScript programming, but you’ll be doing it within the context of another language that transpiles the code ultimately out to regular JavaScript. Those transpilers can always transpile out with whatever the current version of JavaScript is, while making the latest features that are being discussed or the latest little sublanguages, whatever you’d call them, available to people now. Because you already have to have a transpiler anyways with the Typescript and the JSX, having another plugin for your transpiler isn’t a big deal.

Those are really the two big things I see happening in the JavaScript world. Component-driven development and transpiling.

appendTo/DevelopIntelligence:

Any other thoughts to share on JavaScript, Angular, and teaching programming for a living?

Eric:

My philosophy is to give students, lots of opportunity to write code. They’re programmers. We need to hold them to a higher level. They get paid to write code for a living. They should be able to write code, learn great new technologies, and quickly learn how to apply those technologies. I find that in almost all circumstances that when you have that expectation, the students are able to deliver. You’re able to really activate that creative, problem-solving part of their brain as opposed to the passive ‘how fast can I get through the lab’ aspect of their brain.

Many of the students went to college and spent all this money on degrees and everything else. It’s really amazing how many of them really haven’t written a whole lot of code. Not a whole lot of code on their own anyway. They might have copied and pasted a lot of other people’s code. But, if you said build me something from scratch, they really can’t do it. The sad part is that they’re really missing out on one of the greatest joys of being a software developer. The ability to be creative and express how you solve problems. What’s your view of the world? How should the world be organized? The real goal of my classes is not to learn APIs or master patterns, the real goal is for students to solve problems through writing code by exploring their creativity and curiosity.

Truly, software development, unlike most professions nowadays, is a reflection of the person writing the code.

Kind of like a carpenter or a blacksmith 200 years ago or a 100 years ago. Their work would reflect who they are, while today we have machines that do all that for us. Just like a painting reflects the view of the world of the painter, the program reflects the view of the problem from the programmer’s perspective. It’s their ability to contribute something back and really use their gifts and talents and abilities that God gave them and actually make something with it. By not letting them do that in class, you’re really robbing them of a great opportunity.

About the Author:

History and Background of JavaScript Module Loaders

June 13th, 2016

Application logic for web apps continues to move from the back end to the browser. But as rich client-side JavaScript apps get larger, they encounter challenges similar to those that old-school apps have faced for years: sharing code for reuse, while keeping the architecture separated into concerns, and flexible enough to be easily extended.
One solution to these challenges has been the development of JavaScript modules and module loader systems. This post will focus on comparing and contrasting the JavaScript module loading systems of the last 5-10 years.
It’s a comprehensive subject, since it spans the intersection between development and deployment. Here’s how we’ll cover it:

  1. A description of the problems that prompted module loader development
  2. A quick recap on module definition formats
  3. JavaScript module loader roundup – compare and contrast
    1. Tiny Loaders (curl, LABjs, almond)
    2. RequireJS
    3. Browserify
    4. Webpack
    5. SystemJS
  4. Conclusion

The problems

If you only have a few JavaScript modules, simply loading them via <script> tags in the page can be an excellent solution.

<head>
 <title>Wagon</title>
 <!-- cart requires axle -->
 <script src=“connectors/axle.js”></script>
 <script src=“frames/cart.js”></script>
 <!-- wagon-wheel depends on abstract-rolling-thing -->
 <script src=“rolling-things/abstract-rolling-thing.js”></script>
 <script src=“rolling-things/wheels/wagon-wheel.js”></script>
 <!-- our-wagon-init hooks up completed wheels to axle -->
 <script src=“vehicles/wagon/our-wagon-init.js”></script>
</head>

However, <script> establishes a new http connection, and for small files – which is a goal of modularity – the time to set up the connection can take significantly longer than transferring the data. While the scripts are downloading, no content can be changed on the page (sometimes leading to the Flash Of Unstyled Content).  Oh yeah, and until IE8/FF3 browsers had an arbitrary limit of 2 simultaneous downloads because bad people back in the day were bad.
The problem of download time can largely be solved by concatenating a group of simple modules into a single file, and minifying (aka uglifying) it.

<head>
<title>Wagon</title>
<script src=“build/wagon-bundle.js”></script>
</head>

The performance comes at the expense of flexibility though. If your modules have inter-dependency, this lack of flexibility may be a showstopper. Imagine you add a new vehicle type:

<head>
<title>Skateboard</title>
<script src=“connectors/axle.js”></script>
<script src=“frames/board.js”></script>
<!-- skateboard-wheel and ball-bearing both depend on abstract-rolling-thing -->
<script src=“rolling-things/abstract-rolling-thing.js”></script>
<script src=“rolling-things/wheels/skateboard-wheel.js”></script>
<!-- but if skateboard-wheel also depends on ball-bearing -->
<!-- then having this script tag here could cause a problem -->
<script src=“rolling-things/ball-bearing.js”></script>
<!-- connect wheels to axle and axle to frame -->
<script src=“vehicles/skateboard/our-sk8bd-init.js”></script>
</head>

Depending on the design of the initialization function in skateboard-wheel.js, this code could fail because the script tag for ball-bearing wasn’t listed between abstract-wheel and skateboard-wheel. So managing script ordering for mid-size projects got tedious, and in a large enough project (50+ files), it became possible to have a dependency relationship for which there wasn’t any possible order that would satisfy all the dependencies.

Modular programming

Modular programming, which we explored in a previous post, satisfies those management requirements nicely. Don’t head out to celebrate just yet though – while we have a beautifully organized and decoupled codebase, we still have to deliver it to the user.
The stateless and asynchronous environment of the web favors user experience over programmer convenience. For example, users like it when they can start reading a web page before all of its images have finished downloading. But bootstrapping a modular program can’t be so tolerant: a module’s dependencies must be available before it can load. Since http won’t guarantee how long that fetch will take, waiting for dependencies to become available gets tricky.

Javascript Module formats, and their loaders

The Asynchronous Module Definition (AMD) API arrived to solve the asynchronous problem. AMD takes advantage of the fact Javascript is processed in two phases: parsing (interpretation), when the code is checked for syntax, and execution, when the interpreted code is run.

At syntax time, dependencies are simply declared in an array of strings. The module loader checks if it has that dependency loaded already, and performs a fetch if not. Only once all the dependencies are available (recursively including all dependencies’ dependencies) does the loader execute the function portion of the payload, passing the now-initialized dependency objects as arguments to the payload function.

// myAMDModule.js
define([‘myDependencyStringName’, ‘jQuery’], function (myDepObj, $) { ...module code...

This technique solved the file ordering problem. You could again bundle all your module files into one big fella – in any order – and the loader would sort them all out. But it presented other advantages too: there suddenly became a network effect to using publicly hosted versions of common libraries like jQuery and Bootstrap. For example, if the user already had Google’s CDN version of jQuery on their machine, then the loader wouldn’t have to fetch it at all.
Ultimately, AMD’s ‘killer app’ wasn’t even a production feature. The best and least expected advantage of using a module loader came from referencing individual module files during development, and then seamlessly transitioning to a single, concatenated and minified file in production.
On the server side, http fetches are rare, as most files already exist on the local machine. The CommonJS format uses this assumption to drive an synchronous model. The CJS-compatible loader will make available a function named require(), which can be called from within any ordinary Javascript to load a module.

// myCommonJSModule.js
var myDepObj = require(‘myDependencyStringName’);
var $ = require(‘jQuery’);
if ($.version <= 1.6) alert(‘old JQ!’);

CJS eliminates the cumbersome boilerplate syntax of AMD’s define() signature. Back-end pros who use languages like Python often find CJS a more familiar pattern than AMD. CJS can also be statically analyzed more easily – for instance, in the example above, an analyzer could infer that the object being returned from require(‘jQuery’) should have a property named ‘version’. IDEs can use this analysis for useful features like refactoring and autocomplete.
Since require() is a blocking function, it causes the Javascript interpreter to pause the current code and switch execution context to require’s target. In the example above, the console log won’t execute until the code from myDependencyStringName.js has loaded and finished.
In the browser, downloading each dependency serially as the file is processed would result in even a small app having unacceptable load times. This doesn’t mean no one can use CJS in the browser though. The trick comes from doing recursive analysis during build time – when the file has to get minified and concatenated anyway, the analyzer can traverse the Abstract Syntax Tree for all the dependencies and ensure everything gets bundled in the final file.
Finally, ES6, the most significant update to Javascript in many years, added built in support in the form of the new ‘module’ keyword. ES6 modules incorporate many of the lessons learned from both AMD and CJS, but resemble CJS more strongly, especially in regards to loading.

Reasons not to use a module loader

These days, modular programming and module loaders have become synonymous with rich web apps. But using modular programming does not necessarily require using a module loader. In my experience, only the issue of complicated module interdependence qualifies as absolutely requiring a module loader, but many projects have complicated loading infrastructure they just don’t need.
Adding any technology to your stack has a cost: it increases both the number of things that can possibly go wrong and that you need to understand. Many of the benefits of loaders are just that – benefits – and not requirements. Beware the benefits that sound like no-brainers – You Ain’t Gonna Need It, as it’s a subtle form of premature optimization.
Try running your project without a loader at first. You’ll have greater control over and insight into your code. If find you never need one, you’re ahead, and adding one later is not hard.
The same YAGNI logic applies to the features of whatever module loader you choose. I’ve seen many projects use AMD named modules for no benefit whatsoever (and there’s a substantial cost to it as well). KISS.

Tiny loaders

Early on, as AMD emerged as a leading client-side format, the module loading ecosystem exploded to support it. Libraries from this explosion include LAB.js, curljs, and Almond. Each had a different approach, but much in common: they were tiny (1-4kb), and followed the Unix philosophy of doing one thing and doing it well.

The thing they did was to load files, in order, and afterwards call back a provided function.  Here’s an example from the LABjs github:

<script src="LAB.js"></script>
<script>
$LAB
.script("https://remote.tld/jquery.js").wait()
.script("/local/plugin1.jquery.js")
.script("/local/plugin2.jquery.js").wait()
.script("/local/init.js").wait(function(){
initMyPage();
});
</script>

In this example, LAB starts fetching jQuery, waiting until it finishes executing to load plugin1 and plugin2, and waiting until those are finished before loading init.js. Finally, when init.js finishes, the callback function invokes initMyPage.
All these loaders use the same technical mechanism to fetch content: they write a <script> tag into the page’s DOM with the src attribute filled in dynamically. When the script fires an onReadyStateChange event, the loader knows the content is ready to execute.
LAB and curl aren’t actively maintained anymore, but they were so simple they probably still work in today’s browsers. Almond still gets maintained as the minimalistic version of Require.

RequireJS

Require appeared in 2009, a latecomer among the tiny loaders, but went on to gain the greatest traction due to its advanced features.

At its core, Require is not fundamentally different than the tiny loaders. It writes script tags to the DOM, listens for the finishing event, and then recursively loads dependencies from the result. What made Require different was its extensive – some might say baffling – set of configuration options and operating sugar. For example, there are two documented ways to kick off the loading process: either pointing an attribute named data-main of the script tag that loads RequireJS at an init file…

<script src=“tools/require.js” data-main=“myAppInit.js” ></script>
...or invoking a function named require() in an inline script...
<script src=“tools/require.js”></script>
<script>
require([‘myAppInit’, ‘libs/jQuery’], function (myApp, $) { ...
</script>

…but the documentation recommends not using both, without giving a reason. Later, it’s revealed the reason is neither data-main nor require() guarantee that require.config will have finished before they execute. At this point, inline require calls are further recommended to be nested inside a configuration call:

<script src=“tools/require.js”></script>
<script>
require(['scripts/config'], function() {
require([‘myAppInit’, ‘libs/jQuery’], function (myApp, $) { ...
});
</script>

Require is a swiss army knife of configuration options, but an air of automagical uncertainty hangs over the multitude of ways in which they affect each other. For example, if the baseUrl config option is set, it provides a prefix for the location to search for files. This is sensible, but if no baseUrl is specified, then the default value will be the location of the HTML page that loads require.js – unless you used data-main, in which case that path becomes baseUrl! Maps, shims, paths, and path fallback configs provide more opportunities to solve complex problems while simultaneously introducing unrelated ones.
Worth mentioning is possibly the most “gotcha” of its conventions, the concept of “module ID”. Following a Node convention, Require expects you to leave the ‘.js’ extension off the dependency declaration. If Require sees a module ID that ends in ‘.js’, or starts with a slash or an http protocol, it switches out of module ID mode and treats the string value as a literal path.
If we changed our example above like so:

require([‘myAppInit.js’, ‘libs/jQuery’], function (myApp, $) { ...

Require is almost certain to fail to find myAppInit, unless it happens to be in the directory the baseUrl/data-main algorithm returns. As close to muscle memory as typing the ‘.js’ extension is, this error can be annoying until you get in the habit of avoiding it.
Despite all its idiosyncrasy, the power and flexibility of Require won it wide support, and it’s still one of the most popular loaders on the front end today.

Browserify

Browserify set out to allow use of CommonJS formatted modules in the browser. Consequently, Browserify isn’t as much a module loader as a module bundler: Browserify is entirely a build-time tool, producing a bundle of code which can then be loaded client-side.
Start with a build machine that has node & npm installed, and get the package:
npm install -g –save-dev browserify
Write your modules in CommonJS format, and when happy, issue the command to bundle:
browserify entry-point.js -o bundle-name.js
Browserify recursively finds all dependencies of entry-point and assembles them into a single file:
<script src=”bundle-name.js”></script>
Adapted from server-side patterns, Browserify does demand some changes in approach. With AMD, you might minify and concat “core” code, and then allow optional modules to be loaded a la carte. With Browserify, all modules have to be bundled; but specifying an entry point allows bundles to be organized based on related chunks of functionality, which makes sense both for bandwidth concerns and modular programming.
Launched in 2011, Browserify is going strong.

Webpack

Webpack follows Browserify’s lead as a module bundler, but adds enough functionality to replace your build system. Expanding beyond CJS, Webpack supports not only AMD and ES6 formats, but non-script assets such as stylesheets and HTML templates.
Webpack runs on a concept called ‘loaders’, which are plugins registered to handle a file type. For example, a loader can handle ES6 transpilation (Webpack 2.0 handles ES6 natively), or SCSS compilation.
Loaders feed data into a “chunk”, which starts from an entry point – conceptually similar to a Browserify bundle. Once Webpack is set up, chunks are regenerated automatically as assets  change. This can be very powerful, as you don’t have to remember to edit chunks.
The feature that has everybody really excited is hot module replacement. Once Webpack is in charge of your chunks, while running webpack-dev-server, it knows enough to modify code in the browser as you change the source. While similar to other source watchers, webpack-dev-server doesn’t require a browser reload, so it falls into the category of productivity tools that shave milliseconds off your dev process.
Basic usage is beyond simple. Install Webpack like Browserify:
npm install -g –save-dev webpack
And pass the command an entry point and an output file:
webpack ./entry-point.js bundle-name.js
If you’re limiting use to Webpack’s impressive set of defaults, that command power always comes at a cost though. On one project, our team had several difficult problems – transpiled ES6 didn’t work after Webpack chunked it, and then SCSS worked locally but failed to compile in the cloud. In addition, Webpack’s loader plugin syntax overloads the argument to require(), so it won’t work outside of Webpack without modification (meaning you won’t be able to share code between client and server side).
Webpack has its sights set on the being next-generation compiler for the web, but maybe wait for the next version.

Screen Shot 2016-06-13 at 12.27.23 PM

Google Trends’ Take

Source

SystemJS

Wikipedia defines a polyfill as “additional code which provides facilities that are not built into a web browser”, but the ES6 Module Loader Polyfill which SystemJS extends goes beyond the browser. An excellent example of how agnostic modern Javascript has become about the environment it runs in,  the ES6 Module Loader Polyfill can also be used via npm in a Node environment.

SystemJS can be thought of as the browser interface to the ES6 Module Loader Polyfill. Its implementation is similar to RequireJS: include SystemJS on the page via a script tag, set options on a configuration object, and then call System.import() to load modules:

<script src="system.js"></script>
<script>
// set our baseURL reference path
System.config({
baseURL: '/app'
});
// loads /app/main.js
System.import('main.js');
</script>

SystemJS is the recommended loader of Angular 2, so it already has community support. Like Webpack, it supports non-JS file types with loader plugins. Like Require, SystemJS also ships with a  simple tool, systemjs-builder, for bundling and optimizing your files.
However, the most powerful component associated with SystemJS is JSPM, or JavaScript Package Manager. Built on top of the ES6 Module Loader Polyfill, and npm, the Node package manager, JSPM promises to make isomorphic Javascript a reality. A full description of JSPM is beyond the scope of this article, but there’s great documentation at jspm.io, and many how-to articles available.
Comparison Table

Loader CategoryLocal module formatServer filesServer module formatLoader code
Tiny loadersVanilla JSSame structure as local filesSame format as local filescurl(entryPoint.js’)
RequireJSAMDConcatenated and minifiedAMDrequirejs(‘entryPoint.js’, function (eP) {
// startup code
});
BrowserifyCommonJSConcatenated and minifiedCommonJS
inside AMD
wrapper
<script src=”browserifyBundle.js”>
</script>
WebpackAMD and/or CommonJs (mixed OK)“Chunked” – Concat and minify into feature groupsWebpack proprietary wrapper<script src=”webpackChunk.js”>
</script>
SystemJSVanilla, AMD, CommonJS, or ES6same as localSystemJS proprietary wrapperSystem.import(‘entryPoint.js’)
.then(function (eP) {
// startup code
});

Conclusion

Today’s plethora of module loaders constitutes an embarrassment of riches compared to just a few years ago. Hopefully this post helped you understand why module loaders exists and how the major ones differ.
When choosing a module loader for your next project, be careful of falling prey to analysis paralysis. Try the simplest possible solution first: there’s nothing wrong with skipping a loader entirely and sticking with plain old script tags. If you really do need a loader, RequireJS+Almond is a solid, performant, well supported choice. Browersify leads if you need CommonJS support. Only upgrade to a bleeding edge entry like SystemJS or Webpack if there’s a problem you absolutely can’t solve with one of the others. The documentation for these bleeding-edge systems is arguably still lacking. So use all the time you save by using a loader appropriate to your needs to deliver some cool features instead.