Learning the Angular CLI

Exploring the Angular Command Line Interface (CLI)

Installing the CLI

sudo npm install -g @angular/cli
ng --version

Using the CLI

ng --help
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
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

Generating directives

ng generate directive shared/directives/non-numeric --module=shared

Generating services

ng generate service services/api
ng generate service services/api --module=app

Generating pipes

ng generate pipe pipes/phone

Generating models

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 ng build command runs a development build due to which the JavaScript bundles are not optimized meaning they are neither minified nor uglified for performance. Also the bundle names do not contain a hash for cache busting.
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.

Running Tests

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.

The 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

Running the 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.

Conclusion

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.

Essential Extensions for Brackets

Brackets has an extensive array of extensions for enhancing your front-end development workflow.

  • Emmet – The Emmet extension for Brackets, if you take the time to learn it, provides wonderful shorthand snippets for quickly coding in HTML and CSS.
    1. Emmet Plugin
    2. Emmet — the essential toolkit for web-developers
  • Indent Guides – The Indent Guides extension for Brackets adds helpful guides to your code, making it easier to see where one section ends and another begins.
    1. A Brackets extension to show indent guides in the code editor
  • Beautify – The Beautify extension for Brackets does exactly what its name implies. It takes sloppy, unformatted markup and makes it look beautiful by adding spacing and indents that to make it easier to read.
    1. Brackets Beautify 2.x
  • Autoprefixer – The Autoprefixer extension for Brackets parses through your CSS code and adds vendor prefixes to your styles to make it as browser-friendly as possible.
    1. Brackets Autoprefixer
  • Lorem Pixel
    1. Brackets Lorem Pixel
  • CDN Suggestions – Using a Content Delivery Network is a great way to link to commonly used libraries like jQuery and Bootstrap. CDN Suggestions is a plugin that will give you quick access to all of the most popular CDN links available.
    1. CDN Suggestions
  • HTML Wrapper – The HTML Wrapper extension for Brackets provides a great shortcut for surrounding plain text with list item tags, anchor tags, and more.
    1. HTML Wrapper Extension
  • CanIUse – The CanIUse plugin provides a quick-access panel in Brackets where you can search for information about browser compatibility on the CanIUse website.
    1. CanIUse Extension

Useful Tools

  1. embedresponsively.com helps build responsive embed codes for embedding rich third-party media into responsive web pages. — embedresponsively.com
  2. dabblet is an interactive playground for quickly testing snippets of CSS and HTML code — dabblet
  3. An online tool to display formatted source code — Syntax Highlighting
  4. CodePen is all about front end code inspiration, education, and sharing. Enter HTML, CSS, and JavaScript and the combined result is displayed below. – CodePen
  5. JSFIDDLE
  6. JSDB.io is a collection of the best javascript libraries
  7. DevDocs combines multiple API documentations in a fast, organized, and searchable interface.

An Introduction to Yarn Package Manager

In this post, I will introduce you to the Yarn package manager. I will show how to integrate Yarn in your workflow and how to take advantage of its faster performance and consistency. NPM transformed the way we download, install and manage our application’s dependencies. But as you know it is not a perfect tool, even if there was such a thing. It’s slow and inconsistent and it has some security concerns as well. Well Yarn aims to fix that. Over the next few minutes I am going to introduce you to Yarn: A new package manager for JavaScript. Now lets get this out of the way Yarn does not attempt to completely replace NPM. Yarn is a new command line interface designed by the people at Facebook, Google, Exponent and Tilde and it fetches packages from the NPM registry. But it will replace NPM’s command line interface allowing you to do anything that the NPM Client provides.

Getting Started with Yarn is straightforward and of course the first thing that you need to do is install Yarn on your system. Visit Yarn’s website @ https://yarnpkg.com/ and then Click on Install Yarn button. This is going to take you to the installation instructions @ https://yarnpkg.com/en/docs/install for Yarn on your Operating System. Now Yarn needs NodeJS installed. More specifically, it needs NPM. So a lot of these installation instructions are solutions that will also install Node for you. For example, if you are on macOS by using Homebrew you can install Yarn which will also ensure that NodeJS is installed if it’s not already. If you are on Windows, if you install via Chocolatey then it will also ensure that NodeJS is installed. But if you download the installer be sure that NodeJS is installed first. Now this is just one way and chances are very good that you already have NodeJS installed on your computer. So you can install Yarn through NPM. Basically,

$ npm install -g yarn

and that’s going to give you the Yarn CLI. Once you have this installed then all you need to do is use the Yarn command and we will go over the commands that will be replacing NPM in your workflow because that’s essentially what Yarn is going to do. Now when creating a new project the first thing we do is initialize it with npm init and then we go through the process of answering questions and then we end up with a package.json file. And we essentially do the same thing with Yarn. Enter yarn init within the root of your project directory and then we answer the same questions. Now the interface looks a little bit different. Now we still end up with the same package.json file. So let’s say that we want to add React to our project. With NPM you would enter npm install –save react react-dom. With Yarn, we enter the command yarn add react react-dom. Saving is the default here. So we don’t have to say/enter that we want to save it. It is going to be default and it is going to download those dependencies for us. And it’s also going to be faster too because that’s one of the nice things about Yarn.

It’s performance actually comes from 2 separate things. The first is that everything that we install is going to be cached on our system. So whenever we want to install it with another project the first thing it is going to do is check to see if there is a new version. If it’s not new then it is going to use what we have in our cache and that is of course going to be much faster then it is by downloading it over the wire. But the second thing is that Yarn processes in parallel, NPM does not. NPM does things serially which makes sense if one task dependent upon another. But that’s not the case a lot of or even most of the time. So Yarn processes things in parallel which of course is going to be faster. Now I just added react above. Let’s remove that and we would do so by entering yarn remove react react-dom within the root of your project directory. It’s going to remove those packages. But now let’s add them. Let’s say we want to add a specific version, for e.g., version 15.3.1 of react and react-dom. So we will enter yarn add react@15.3.1 react-dom@15.3.1 and that will install that particular version for our project.

Once this is done installing, we are going to look at not just the package.json file but another file called yarn.lock. Because the yarn.lock file is very important with Yarn. First of all the package.json file is standard. We have the dependencies listed as well as their versions. Now one of the problems with NPM is that whenever your committed this to your repository and somebody else cloned it and did npm install and of course it is going to install the dependencies but you aren’t always guaranteed to get that exact version. In some cases, it might download a patch for that version which then you have 2 people working on essentially the same project but using different dependencies and that is a huge problem. So the folks that created Yarn decided to create this lock file. If you look at yarn.lock, the very first thing it says THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. This is created by Yarn whenever you install dependencies and it specifies the package as well as the version. So this is the file that you definitely want to commit to your repository because then whoever installs the packages using Yarn is going to get the same exact packages that are mentioned within the lock file. So if you look into yarn.lock file you will see both react & react-dom of version 15.3.1 installed.

Let’s say we are ready to update to version 15.4.0. For that we enter yarn upgrade react@15.4.0 react-dom@15.4.0 and this is going to update just those dependencies. Looking back into yarn.lock you will see those updated version numbers. So anytime you add, remove or upgrade a package, Yarn is going to update the lock file so that all the versions for all the dependencies are going to be consistent for everybody working on the same project and that is extremely important. That is also the main reason why Yarn was created to begin with. Now its worth noting that the packages that Yarn installs are from the NPM registry. There is not this new registry that have yarn packages. It’s using NPM. So in that sense there are a lot of related commands that are the exact same as NPM.

For example, we have already seen yarn init. There is also link, there is outdated, publish, run, cache clean, login, logout and test. All of these are the same commands as you would run with npm. However, Yarn has few things which NPM does not. For example, if we wanted to inspect all the licenses of our dependencies we would enter yarn licenses ls and it would list all our dependencies, their versions, their license and the URL for their repository. We can also generate our license dependency disclaimer by entering yarn licenses generate-disclaimer and that would generate that disclaimer. Finally, we can find out why we have a particular dependency. For example, let’s say we have a dependency called promise and so using  yarn why promise we can see why we have this promise dependency. Running yarn why promise gives us one of the following info i.e. This module exists because “react#fbjs” depends on it. 

We live in a world where there are new tools released almost on a daily basis and many of those tools are questionable. I mean there is no question that they are useful but you have to question whether or not it’s something that you want to spend time on. Well, Yarn is not one of those tools. Yes, it replicates NPM’s functionality  but it also brings some very useful things to the table. I mean the performance alone is the reason to use Yarn. So install it today and use it in your workflow.

PostCSS – First Look

Introduction

PostCSS is an engine/tool for processing/transforming CSS with JavaScript. It help’s us writing CSS faster and more efficiently. There are different plugins that we can use with PostCSS. Some of them include cssnano which helps in compressing the CSS files, Autoprefixer which programmatically adds prefixes to the CSS files, making things like Flexbox easier to code for modern browsers, adding future CSS syntax/features that can work with older browsers using cssnext & finally PreCSS pack, which lets us use a Sass-like syntax for working with our projects.

What is PostCSS?

  • PostCSS at its core is an engine for transforming CSS with JavaScript.
  • Uses NodeJS and installs through NPM which allows it to take care of different transformations.
  • It can also work with different build tools like GulpJS, GruntJS, Broccoli, and others to handle the transformation process.
  • It is 3 – 30 times faster than other tools since it uses NodeJS and has a modular architecture which makes it a lot more efficient. Sass in contrast, needs Ruby installed and when you add some extensions they get added as gems which makes the applications run a little bit slower.
  • The first difference that you will notice between PostCSS and Sass or LESS is the super small size of the core engine which makes it more efficient.
  • Another big difference between PostCSS and other tools is that its not just limited to pre-processing. PostCSS can also work as post-processor which means it can convert future CSS syntax to CSS, but also do tasks like adding prefixes to a finished stylesheet.
  • Although PostCSS is new it has a large plugin base.
  • Can handle an amazing number of tasks including support for future CSS features in older browsers like variables or mixins. It can work like Sass providing features like nesting and variables.
  • Because of PostCSS’s modular architecture we can use it with our exisiting tools.
  • Because PostCSS is modular, fast and flexible it’s quickly becoming a serious contender to take care of common tasks.

What you need to work with PostCSS?

  1. NodeJS
  2. In order for PostCSS to work, it needs to be integrated into your workflow through a build tool. We can use many different tools, including Gulp, Grunt, Webpack or Node.js itself.

Resources

  1. PostCSS on GitHub.
  2. Gulp PostCSS Plugin on GitHub.
  3. cssnano and cssnano on GitHub.
  4. Autoprefixer PostCSS Plugin on GitHub.
  5. cssnext PostCSS Plugin.
  6. PreCSS on GitHub.

Webpack

In this post I will talk about Webpack a very popular build tool in the React community. Now if you are used to tools like Grunt or Gulp you can think of Webpack as being something similar. Now Grunt and Gulp are general purpose task runners. So they can technically do what Webpack can do but requires configuring a bunch of plugins. Webpack on other hand is a complete Module Bundler. So what’s a module bundler?

Now if you look at any React project or for that matter any web project, it contains a bunch of static assets like JavaScript, CSS, Sass files, Images, Fonts and so on. Each of these in the Webpack parlance is called a module. These modules can depend on each other. Webpack being a module bundler, combines all of these modules into a highly optimized bundle which can then be deployed onto the web. Webpack also takes care of automatically bundling these modules anytime they change which gives us a nice development time workflow.

Now if we probe a little deeper into Webpack, we will see 3 fundamental concepts – Loader, Plugin and Chunk. A Loader is responsible for loading a single file and also optionally transforming it. As an example, we have the Sass loader which loads the Sass files and transforms it to CSS. A Plugin can extend the behavior of Webpack and also operate on multiple files at once. As an example, we have the HTML Webpack plugin which can create the index.html based on all the bundles we have in a project. Lastly, Chunk is the output of Webpack. There could be more than one chunk created depending on how the project is structured. Loaders and Plugins can both contribute in creating the Chunk, also known as the Bundle.