March 14, 2019
The JAMstack Architecture
So what are the advantages of using the JAMstack? For starters, JAMstack offers better performance compared to server-side rendered applications, especially if you host your static site in a CDN, you can get subsecond access times in this way. Static sites offer better security because they offer a reduced attack surface compared to dynamic sites. Removing system components, like a database from the equation, can have significant advantages, including eliminating SQL injection attacks. Moving he business logic away from your app also decreases the risk of an attack. Now it’s the responsibility of API creators to secure that part of the application. Static sites are cheap to host and scale. You can serve your site in more places faster. Finally, if your goal is good SEO performance, static sites can also dramatically improve the discoverability of your site.
Now let’s see when a site does not adhere to JAMstack. If you build a site with a server-side render framework like a content management system (CMS), such as WordPress, for instance, your site does not adhere to the JAMstack framework. The same applies to a web-application created with more established frameworks like C#, and .NET, Java, and Spring, and Node, and Express just to name a few. These frameworks render your application in the server, hence not adhering to JAMstack either. A less intuitive example is a single-page application created with a front-end framework like Angular, Vue, or React that is isomorphic in nature that is a sort of a blended server-side rendered application and a single-page application.
So what does Gatsby and JAMstack have in common then? Well, Gatsby adheres to all tenants in the JAMstack, and does it magnificently using the best technologies and workflows that work in tandem to provide a great user experience for developers. Now that we have a clear understanding of JAMstack and its advantages, it’s time to explore Gatsby in more detail. We will do that next.
What is GatsbyJS?
GatsbyJS is a modern front-end framework for creating static sites and applications. It’s been built upon modern technologies such as React, GraphQL, and Webpack, amongst other front-end technologies. One thing that makes Gatsby unique is that you don’t have to know React or GraphQL to start working with Gatsby. You can learn Gatsby as a way to introduce yourself to the world of React, GraphQL, and modern front-end development in general. Its creators have taken out the guesswork of configuring a modern workflow to build sites based on these technologies; therefore, creating sites with Gatsby is fun, productive, and easy, and the results are great. I mentioned React and GraphQL, but what are these and what do they do?
GraphQL is also a technology created by Facebook and is a query language that allows you to query for data in a declarative way by describing the data you intend to get from a data source. It lets you specify the data your application needs and gets that data in the format you initially requested. We will be using GraphQL for querying data when building blog site.
Okay, another example. Let’s say you want to create a page with a list of popular products that your company sells. This data changes once every three months or so and resides in a database. The traditional approach was to create a server-side rendered application that connects to a database, generally, through a endpoint exposing this data and then generate the page on the fly at runtime with the desired information. With Gatsby, we take a different approach. We call the endpoint with GraphQL, fetch the data you need, and then create a static HTML page with the required data. The information is only queried once and served from the server as a prebuilt static HTML file. Another cool thing about Gatsby is its rich plugin ecosystem which brings a lot of functionality to Gatsby.
Alright, we went over React, GraphQL, and the merits and benefits of static sites and using Gatsby. Gatsby is the way to go when you want to build a site that is fun to develop, uses a modern workflow and future-proof technologies, adheres to the tenants of JAMstack, is fast, secure, inexpensive to host, and has excellent SEO capabilities.
Gatsby goes beyond creating static sites. React and GraphQL are used by thousands of companies and developers to create sophisticated web applications. Since Gatsby uses React, we can use Gatsby to develop sophisticated web applications as well.
Lastly, I want to go over browser support for Gatsby briefly. Gatsby currently supports the same browsers as the current stable version of React, that is Internet Explorer 9 and above, as well as the most recent versions of other popular browsers. They are also known as ever-green browsers, in other words, browsers that self-update. Next, let’s go over the installation process of GatsbyJS.
March 28, 2018
In the context of web apps, animation is nothing more than the visualization of change over a specified duration. This visualization of change is very important because when done right we can use this to dramatically increase the user experience of an app and make our apps feel more refined and well designed.
February 24, 2018
Exploring the Angular Command Line Interface (CLI)
Installing the CLI
sudo npm install -g @angular/cli
Using the CLI
ng build --help
Creating New Angular Projects
The ng new command
ng new app-name
New project generation options
ng new --help
ng new app-name --routing
ng new app-name --style=scss --routing --dry-run
ng new app-name --style=scss --routing --prefix=vsrao
Serving Angular Applications for Development
The ng serve command
ng serve --help
ng serve --open
Customizing the development server
ng serve --port=8000 --open
ng serve --host=whatever.dev.company.com --open
Generating Angular Application Code
Creating new code with blueprints
With the Angular CLI you can generate the different entities used to build your application. You will be able to easily generate Components, Directives, Services, Pipes, Models and Interfaces, Route Guards and Modules. When generating a blueprint, your command will follow the following template:
ng generate [schematic] [name] [options...]
ng generate --help
Available schematics: application, class, component, directive, enum, guard, interface, module, pipe, service, universal and appShell.
Generating components and modules
ng generate component contact-list --dry-run
ng g c contact-list --dry-run
ng g c contact-list --dry-run --flat
ng g c contact-list
ng generate module shared
ng generate component shared/avatar --module=shared
ng generate directive shared/directives/non-numeric --module=shared
ng generate service services/api
ng generate service services/api --module=app
ng generate pipe pipes/phone
ng generate class models/contact
Generating interfaces and enums
ng generate interface models/contact
ng generate enum models/contact-type
Generating route guards
ng generate guard auth
Building Angular Applications
A build pipeline for an Angular app
There are many steps involved in building an Angular application. Since Angular applications are written in TypeScript and ES6 and beyond, the build pipeline is quite involved. We need to Transpile TypeScript and ES6+ code, bundle our application into one file, or split across many, minify files by removing newlines and white space, mangle our application bundles to make files even smaller, and also generating source maps. Aside from that, we also need to deal with CSS and other assets, such as compiling from Sass to CSS, possibly inlining CSS, having scoped styles, and copying or inlining images. As you can see the process is very involved, but the Angular CLI takes care of all this for us using Webpack under the hood, all with a simple command,
ng build. The
ng build command also comes with several options.
Configuring different build options
By default, the
A production build can be run using
ng build --prod. For generating source maps in a production build we need to use the
ng build --prod --sourcemap command. Lastly, if you wish to analyze the generated bundle files, using a tool such as webpack bundle analyzer use the
ng build --prod --stats-json command. Running this command will generate a stats.json file, which you can then upload on webpack.github.io/analyse/ . On this site, you can analyze the different bundles that the build pack run generated for you. You can analyze chunks, the assets, and see the size of each of them.
Setting up build scripts
In the package.json file, we can setup the below npm scripts:
"build:dev":"ng build --stats-json"
"build:prod": "ng build --prod --stats-json"
Setting up npm scripts will make automation much easier.
Built-in test runners and scaffolding
When you create an Angular application using the CLI, a testing pipeline is already set up for you. To run your unit tests, a karma configuration file, karma.conf.js is generated. Karma is used as a test runner using jasmine as a testing framework, and is set up, by default, to run your tests in Chrome. Additional setup can be seen in test.ts. Essentially, this provides additional setup to initialize the Angular testing environment. You can write your tests in TypeScript and the CLI will take care of transpiling that for you.
ng test command
In order to run your unit tests, you use the
ng test command. This will take all of your spec files, transpile them in memory, and run your unit test in Chrome.
Test run options
ng test command runs the test in watch mode. However, if you prefer not to do that, you can use a single run flag. By running the
ng test --single-run command the test will only run once and then exit. This will be needed in a Continuous Integration environment.
You can also generate code coverage reports when running your tests. To do so, you need to use the code coverage flag. Running
ng test --single-run --code-coverage command will not only run your tests but will also generate code coverage reports using Istanbul. Once it is complete, it will create a new coverage folder, with an index.html page for your report.
Ejecting from the Angular CLI
The tooling provided by the Angular CLI is quite extensive. It can generate applications, application code, and also set up build and testing pipe lines for you. However, it is not uncommon for a development team to ask specific needs over the build process, in order to have finer control. It is for these purposes that the Angular team created an eject feature. You can use this feature if you feel that you want to manually take care of running and building your application. To do so, you can use the
ng eject command.
The Angular CLI is truly a great tool that will allow you to be productive building Angular applications. I recommend subscribing to notifications on this GitHub repository – https://github.com/angular/angular-cli/, as it will allow you to keep up to date with new features and be notified of new releases. The Angular team have some great things planned for the CLI. I also recommend subscribing to the official Angular Blog – https://blog.angular.io/ for keeping up to date.
November 11, 2017
You can start using React 16 today. When you install React in a project or create a new app using the create-react-app tool, it will automatically install the latest version of React and ReactDOM. As mentioned above, React 16 is backwards compatible. So if you are currently running your app on a previous version of React without any console errors or deprecation warnings, updating to React 16 will not break your app. It should be a seamless transition. Now with a complete rewrite of the React Library comes a few minor breaking changes that only affect uncommon use cases. You can view all the breaking changes. A welcome change is that React is now available under the MIT license. The uncertainties created by Facebook’s previous BSD+Patent’s open source license was a concern to many developers, startups and companies using React. So now React licensing is more flexible. You can use React in your project without having to worry about the previous patent’s clause. Now if you are not able to upgrade immediately to version 16, React 15.6.2, was also published under MIT. Also note, the React 16 update does not mean that whatever you have learned so far about React is immediately obsolete. The API itself hasn’t changed, and most of the skills you have learned are still important, fundamental skills you will continue to use. So if you are eager to learn about everything that is new in React 16 next I will cover the new component life cycle method and error handling feature that lets us catch and manage errors when rendering React components.
Take Control of Errors with
componentDidCatch(). This life cycle hook gets triggered whenever a childs component render or life cycle methods throw an error. When an error occurs,
componentDidCatch() catches the error and instead of crashing the entire app, the app continues to run as normal displaying all the UI except for the faulty component. You can even display a fallback UI to replace the component that crashed.
Catching Errors with Error Boundaries
componentDidCatch() lifecycle method comes a new concept of an error boundary. Error boundaries are wrapper components that use
componentDidCatch() to capture errors anywhere in their child component tree and display a fallback UI in its place. They provide an easier way to keep the error catching and conditional rendering logic reusable and maintainable in your app. You create an error boundary as a class component. Any errors caught in the component tree get reported up to the Error Boundary’s
componentDidCatch() method thereby providing a handy way of sending error reports to an error tracking or monitoring service. The
componentDidCatch() method take two arguments to help you track and investigate errors,
error – the error instance itself, and
info which contains the component stack trace or the path in the component tree leading up to the offending component. The component stack trace contains helpful information for sorting and resolving errors. The
componentDidCatch() method and Error Boundary work like
try/catch statements for your React components. They provide a more consistent and dependable way to catch and deal with errors.
Note: Error Boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself.
New Return Types
React 16 supports new return types that let your render less DOM nodes. For example, React no longer requires that the
render() method returns a single React element. You are able to render multiple sibling elements without a wrapping element by returning an array. The other new return types React 16 supports are strings and numbers. Eliminating
divs or any extra element added just to wrap your React component tree or returned content leads to overall cleaner and smaller components.
Render Children into Other DOM Nodes with Portals
React 16 introduces a new way of rendering into the DOM. You can render children into a DOM element that exists outside of your apps main DOM tree with a new feature called Portals. For example, in your index.html template you will usually have a
div with the id
root which is where your entire app is rendered into the DOM via
ReactDOM.render. To create a portal, you add a second element that’s a sibling of your root
div as shown below.
<div id="root"></div> <div id="my-portal"></div>
Then you can render specific parts of your component tree inside the sibling
div with the new
createPortal() function. The
createPortal(child, container) function accepts two arguments, child and container. The first argument
child is the content you want to render. The second argumnet
container is the DOM element where the content is going to render.
createPortal() provides a hook into HTML that’s outside the
div. As mentioned in React docs, portals are useful when a parent component has an
overflow hidden or
z-index style, but you need the
child to visually break out of its container. So a handy use case for portals is when creating modal windows or overlays. What’s interesting about portals is that the components they render are recognized as regular child components of the app. In other words, even though portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. For example, an event triggered from inside a portal still propagates or bubbles up to the parent component.
Returning null from
React 16 lets you decide if state gets updated via
setState to prevent unnecessary DOM updates. In your events you can check if the new value of the state is the same as the existing one. If the values are the same, you can return
null will not update state and trigger a re-render. React 16 provides state performance improvements that let you prevent an update from being triggered by returning null for
setState if the new value of state is the same as the existing value. Preventing unnecessary state updates and re-renders with null can make your app perform faster.
September 24, 2017
In the upcoming 9 posts to follow we will learn how to program Arrays without loops using just a few simple functions. We will learn the correct approach towards asynchronous programming and avoid making common mistakes. By the end of these 9 posts we will have the tools, concepts, and libraries required to be an asynchronous programming expert!