From Zero to Hero with Angular CLI: A Complete Workflow

Anton Ioffe - November 29th 2023 - 9 minutes read

Welcome to the realm of streamlined development, where the Angular CLI stands as a powerful ally in your web development endeavors. Journey with us through the intricacies of Angular CLI, as we transform from zero to hero, mastering the workflow that primes you for excellence in modern web applications. From erecting a robust development environment to harnessing the prowess of sophisticated build optimizations and seamless library integrations, this article lays out a complete workflow that sharpens your Angular expertise. Prepare to delve deep into the command-line techniques and best practices that will elevate your projects, as we guide you through a path laden with professional insights for crafting elegant, efficient, and scalable Angular applications.

Setting Up a Robust Angular Environment with CLI

Establishing a local development environment for Angular requires first the installation of its foundational tools, Node.js and npm (node package manager). To assure the sustainability and compatibility of your development environment, it's imperative to install the latest stable versions of these tools. To verify that you're on the right track, run node -v and npm -v in your console, which should output the current versions installed on your system.

Having these prerequisites in place, the next step is to globally install the Angular Command Line Interface (CLI) using npm. The installation command npm install -g @angular/cli will equip you with a seamless interface for creating, managing, and architecting your Angular applications. The global flag (-g) ensures that you can run the CLI from any directory in your system. While global installation is a common approach, it's important to note that permissions on your machine may necessitate the use of sudo for a successful installation.

Once the Angular CLI is installed, a simple command ng new 'my-new-angular-app' initiates the scaffolding of a new Angular project. This command creates a new directory with the specified project name and sets up the fundamental structure. The CLI automatically handles the installation of Angular libraries and their dependencies, TypeScript configuration, and installs Karma & Protractor for testing, paving the way for a frictionless start.

Navigating into your project's directory, cd my-new-angular-app, presents you with a wealth of auto-generated files and folders. The most pertinent among these is the /src/ directory, where your application's source code will reside. Other directories like /e2e/ for end-to-end testing and node_modules/ for third-party libraries are essential but won't require immediate attention when starting your development.

Lastly, to confirm that your Angular environment is correctly set up and functioning, you can serve your new project locally using the ng serve command. This spins up a local development server and watches for changes in your code, reflecting them in real-time. You can now access your project at http://localhost:4200/ in your browser. This immediate feedback loop is invaluable in ensuring that your development environment is robust, stable, and primed for productivity.

Diving Deep into Angular CLI Commands and Flags

Understanding Angular CLI commands and their myriad of flags can significantly enhance your workflow. Consider the ng serve command, which launches the development server and watches for file changes. While convenient for instant feedback, this can be further optimized. For instance, adding --prod flag simulates a production environment, which is useful for spotting issues before deployment. Similarly, the --hmr flag enables Hot Module Replacement, allowing developers to update modules while the application runs without a full reload.

The ng build command is equally versatile. It offers an array of flags like --aot for Ahead-Of-Time compilation, amplifying performance by pre-compiling application components. Conversely, the --watch flag creates a development build and watches for file changes, contrasting with the --prod flag that creates an optimized production build. The --source-map flag can be essential during debugging, generating source maps that map the compiled code back to the original source.

For testing, ng test initiates the Karma test runner to execute unit tests. Developers can make use of --code-coverage to generate coverage reports, identifying untested parts of the codebase. Moreover, the --browsers flag allows specifying different browsers to test the application in various environments. In a Continuous Integration (CI) context, running tests with --watch=false ensures the process completes after a single run, which is crucial for CI workflows.

Each of these commands can be tailored even further. Flags like --configuration allow for specifying different build configurations, ensuring that the right environment settings are applied. The --output-path flag redirects the output to a specified directory, beneficial when integrating with other tools or deploying. It is imperative to familiarize oneself with the --help flag, which reveals additional, context-specific options for every command, tailoring your command line strategy to the task at hand.

Avoiding pitfalls is as important as leveraging the right flags. A common oversight is using --prod without adequate testing, which can lead to deployment issues due to differences between development and production builds. Over-reliance on --watch may impact performance and distract from deliberate, structured development practices. As with any powerful toolset, judicious application determines whether you reap the rewards of efficiency or face the woes of inadvertent missteps. Reflect on your current practices: Could they be refined by exploiting a yet untried combination of Angular CLI commands and flags?

Optimizing the Development Experience with Angular Schematics

Angular Schematics serve as a powerful code generation and transformation toolkit that integrates seamlessly with the Angular CLI. By leveraging this tool, developers can customize and automate the creation of commonly used patterns and support consistent architectural decisions throughout the application's lifecycle. When the requirements of a project evolve, a schematic allows developers to generate necessary files and configuration without manual intervention, thereby minimizing human error and ensuring that the project adheres to the established best practices.

Schematics can dramatically streamline the development process, especially during the scale-up phase of a project. When new components, services, or modules are required, executing a simple command such as ng generate component componentName can save significant time and effort compared to manual file creation and wiring. Furthermore, schematics are not just for generating boilerplate code; they can also modify existing files, inject dependencies, and more, which can be indispensable when refactoring or enhancing features.

The true strength of schematics lies in their customizability. Teams can create their own sets of schematics that align with their specific workflows, coding standards, and architectural guides. This not only enhances productivity but also ensures uniformity across the code base, which is particularly beneficial for large teams where consistency in design and implementation is crucial to maintainability.

One common mistake is over-reliance on the default schematics, which might not always align with project-specific requirements. Instead, developers should take advantage of custom schematics to mold the CLI's behavior to their needs. Correctly implemented custom schematics reduce repetitive tasks to a minimum while adapting the project structure to the unique ecosystem of the application being developed.

Consider how you might leverage Angular Schematics in your current project. Are there repetitive patterns in your codebase that could be encapsulated by a schematic? Could introducing custom schematics enforce your project's architecture more rigidly, making it easier for new developers to contribute without straying from established practices? Exploring these possibilities could unlock a new level of efficiency and consistency in your Angular development workflow.

Advanced Angular CLI: Customizing Builds and Proxies

Angular CLI offers an abstraction over complex configurations, which is good for most use cases but can feel restrictive when specific customizations are needed. Fortunately, Angular CLI's build process can be customized through angular.json file without needing to eject from its managed setup. Developers can specify different configurations for different environments by creating configuration sections within the "architect" node. For instance, setting different API URLs for development and production environments can be achieved by introducing environment-specific variables in 'environments' folder and referencing them in the application code.

Understanding the Angular CLI build process allows developers to utilize proxies for API requests during development. The 'proxy.conf.json' file can be created at the root of the project and referenced in the "serve" options within 'angular.json'. Through the proxy configuration, developers can redirect API calls from the Angular development server to a backend server, circumventing same-origin policy issues during development. This setup emulates production environment closely and streamlines development without modifying the application code for CORS (Cross-Origin Resource Sharing) concerns.

One of the most commonly overlooked yet powerful features of Angular CLI is the ability to further modify Webpack configuration indirectly, utilizing the 'custom-webpack' builder and schematics. By changing the default Angular builder in 'angular.json' to '@angular-builders/custom-webpack:browser' for build and serve, developers gain the control to extend the default Webpack configuration provided by Angular CLI. This is done by adding a webpack.config.js file where custom loaders, plugins, or any other Webpack-specific configurations can be introduced.

Handling the build optimizations and intricacies of Angular CLI custom builds requires a thorough understanding of both Angular and Webpack ecosystems. Opting for AOT compilation by default and leveraging tree shaking and minification are key considerations. Furthermore, for larger projects, the use of lazy-loaded modules and differential loading for modern versus legacy browsers are pivotal in improving the performance of Angular applications.

However, with great power comes great responsibility. Customizing Angular CLI builds should be done cautiously, keeping maintainability in mind. Overriding configurations can complicate the upgrade process for future Angular versions and potentially introduce subtle bugs. Developers should thoughtfully consider if a customization is truly necessary and if it aligns with the long-term goals of the project. Does the benefit of the customization justify the extra complexity it introduces? How will it impact new team members who are introduced to the project? Addressing these questions ensures that customizations are both essential and sustainable.

Incorporating Third-Party Libraries and Angular CLI Updates

When incorporating third-party libraries into an Angular project, aim for those that offer an NgModule to fully harness Angular's dependency injection system. Install these libraries through npm and import their corresponding modules to ensure efficient integration. Always follow the library's installation and usage guidelines to ensure compatibility with your project's structure.

Keep the Angular CLI and project dependencies current by using the ng update command. Time these updates strategically within the development cycle to prevent disruption. A well-planned update process minimizes unforeseen issues and integrates smoothly with non-critical phases of the project.

Assess the compatibility of third-party libraries with your Angular version carefully to avoid integration issues. Rely on npm commands rather than manual edits in package.json or angular.json for managing packages. This method avoids conflicts and fosters a stable development environment by leveraging npm's conflict resolution capabilities.

Updating the Angular CLI requires diligence. Before applying an update, familiarize yourself with the release notes and test the changes on a separate branch. Only after verifying compatibility through rigorous testing—including unit and e2e tests—should you merge the updates. This safeguard maintains the integrity of the application through each version change.

A collaborative approach to dependency management and update schedules is key. Consistent and regular updates reduce technical debt and keep the project updated with the latest technology. While automation is beneficial, human oversight is crucial to ensure the updates serve the project's objectives and preserve stability.

Here's an exemplary approach to integrating a third-party library by importing the module:

import { NgModule } from '@angular/core';
import { MyLibraryModule } from 'third-party-library';

@NgModule({
    imports: [
        MyLibraryModule,
        // Additional imports...
    ],
    // Other metadata properties...
})
export class MyFeatureModule {}

Importing a third-party module, as shown above, follows best practice within an Angular module, avoiding conflicting versions and peer dependency issues. Confirm compatibility with your Angular version before installation, and rely on npm or yarn to handle any peerDependencies. These preventive measures during the setup phase spare your project from later headaches and ensure a harmonious build process.

Summary

In this article, the author explores the Angular CLI and its role in modern web development. They provide a step-by-step guide to setting up a robust development environment, diving into Angular CLI commands and flags, leveraging Angular Schematics for code generation and customization, customizing the build process, and incorporating third-party libraries. The article emphasizes the importance of staying up-to-date with Angular CLI updates and offers a challenging task for readers to think about how they can leverage Angular CLI to optimize their own development workflows and enhance their Angular expertise.

Don't Get Left Behind:
The Top 5 Career-Ending Mistakes Software Developers Make
FREE Cheat Sheet for Software Developers