Introduction to Angular CLI Builders

In this blog, we’ll look at a new API in Angular CLI that allows us to add new CLI features and enhance existing ones. We’ll go over how to interact with this API and what extension points we can use to extend the CLI’s features.

With Angular 8, the B…


This content originally appeared on DEV Community and was authored by Tarun Gurang

In this blog, we'll look at a new API in Angular CLI that allows us to add new CLI features and enhance existing ones. We'll go over how to interact with this API and what extension points we can use to extend the CLI's features.

With Angular 8, the Builders API was released, and it includes the ability to override commands such as ng build, ng test, and ng lint. Not to be confused with Angular Schematics, which can be used to add custom commands to ng generate or provide support for ng add.

History

We introduced the workspace file (angular.json) in the Angular CLI about a year ago, and we reworked several key principles of how its commands were implemented as a result. We ended up placing the following commands in boxes:

  1. Commands on the schematic diagram. We've probably heard of Schematics, the CLI's code generation, and modification library. It launched in version 5 and is now used in most commands that interact with our code, including new, generate, add, and update.
  2. Miscellaneous commands. help, version, config, doc, our newly added analytics, and our Easter eggs are all commands that are specially coded and are not unique to a project.
  3. Task commands. This category translates to "running a process on other people's code." The build is a good example, but linting and testing are also good examples.

This was originally designed to allow people to replace their webpack configuration or migrate to a different underlying build implementation; we started designing it a long time ago. We eventually came up with a basic task-running method that we could use as an experiment for the time being. This API was given the name "Architect" by us.

The architect was a success with people who wanted to use a custom build or third-party libraries who wanted to customize their workflow, even though it wasn't officially sponsored. Nx used it to run Bazel commands, Ionic used it to run Jest unit tests, and users could use tools like ngx-build-plus to extend their webpack setup. And this was just the beginning.

An enhanced version of this API is now stable and officially supported in Angular CLI version 8.

Conceptual Overview

The CLI uses the Architect API for command implementations since it has tools for scheduling and coordinating tasks. It uses the workspace's angular.json to resolve tasks and goals to their builder implementation, and builders as the implementation of a task (which can schedule other builders).

It's a generic framework that's designed to be adaptable and forward-thinking. It includes APIs for progress reporting, logging, and testing, as well as the ability to add new features.

Read More: How To Implement File Upload In Angular?

Builders

Builders are functions that enforce the logic and behavior for a process that can be used instead of a command, such as running a linter.

A builder is given two arguments: an input (or options) and a context that allows the CLI and the builder to communicate. The separation of concerns is the same as with Schematics: the CLI user provides options, the API provides context, and we provide the behavior. It can be synchronous, asynchronous, or watch several values and output them. BuilderOutput is the only output form that includes a success boolean field and an optional error field that can contain an error message.

Workspace File and Targets

The angular.json workspace file is used by Architect to resolve targets and their options.

The workspace is divided into projects by angular.json, and each project has a set of targets. Our default application, which is generated when we run ng new, is an example of a project. Create, which is run automatically while using ng build, is one of the project objectives. That target has three keys (by default):

  1. builder. When running this target, the name of the builder to use is of the form packageName:builderName.

  2. options. While running this target, a default set of options is used.

  3. configurations. When running this target with a particular configuration, a map of name to options has been used.

When executing a target, the options are resolved by first using the default options object, then overwriting values from the configuration used (if any), and finally overwriting values from the overrides object passed to scheduleTarget (). The overrides object in the Angular CLI is created using command line arguments. This is then applied to the builder's schema, and only if it satisfies, seems to be the context created and the builder itself executed.

Creating an API Builders Project

Let's take a look at the API before we start writing our builder.

1.BuilderContext

2.BuilderOutput

3.createBuilder

Looking for Genuine AngularJS Development Company? Enquire Today.

BuilderContext

Let's take a look at some of the useful methods and properties that are available:

reportStatus: To report the status of a running task to the command prompt, use the reportStatus method.

logger: For logging purposes, logger offers methods such as log, debug, info, warn, error, and fatal.

scheduleTarget: This approach allows us to schedule other tasks using the given config; for example, running the build task as part of our task.

createBuilder

This is the builder's entry point; it may return a promise or an observable of type BuilderOutput.

BuilderOutput

The following values can be returned by BuilderOutput:

error: It is an error message to send to the application. it is an optional value

info: this function returns a [key, value] pair and it is optional.

success: It is required and can return a true/false value.

target: It can return a configuration project and target this is optional.

Index.ts

export default createBuilder<options>(
  async (options: Options, context: BuilderContext): Promise<builderoutput> => {
context.reportStatus(`Executing "${options.command}"...`);
const configuration = options.configuration ? options.configuration : 'production';
    const build = await context.scheduleTarget({
      target: 'build',
      project: context.target !== undefined ? context.target.project : '',
      configuration
});
    const test = await context.scheduleTarget({
      target: 'test',
      project: context.target !== undefined ? context.target.project : ''
});
let buildResult = await build.result && await test.result;
return { success: buildResult.success };
  });
</builderoutput></options>

2.To test the builder locally, use the npm run build command.

3.To link the package locally, use the npm link command.

4.Using the CLI, create a new Angular application.

5.Run npm link @example/command-runner we may modify the package name to fit the one mentioned in the builder's package. JSON is a type of data.

6.In angular.json, add the following configuration.

"[our-command]": {
  "builder": "@example/command-runner:command",
  "options": {
    "command": "[our-command]",
    "args": [
      "src/main.ts"
    ]
  }
}

7.To test the builder, type ng run [project-name]: [our-command] or ng deploy if our command is for deploying. This will be available after the release of Angular CLI 8.3.0.

We can also use it across multiple applications by publishing it on npm.

Conclusion

The use case for the builder’s API is even broader, and there are already many custom builders available. The CLI team decided to make ng deploy the command available after the custom builder to deploy became so popular.


This content originally appeared on DEV Community and was authored by Tarun Gurang


Print Share Comment Cite Upload Translate Updates
APA

Tarun Gurang | Sciencx (2021-11-03T10:24:00+00:00) Introduction to Angular CLI Builders. Retrieved from https://www.scien.cx/2021/11/03/introduction-to-angular-cli-builders/

MLA
" » Introduction to Angular CLI Builders." Tarun Gurang | Sciencx - Wednesday November 3, 2021, https://www.scien.cx/2021/11/03/introduction-to-angular-cli-builders/
HARVARD
Tarun Gurang | Sciencx Wednesday November 3, 2021 » Introduction to Angular CLI Builders., viewed ,<https://www.scien.cx/2021/11/03/introduction-to-angular-cli-builders/>
VANCOUVER
Tarun Gurang | Sciencx - » Introduction to Angular CLI Builders. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/03/introduction-to-angular-cli-builders/
CHICAGO
" » Introduction to Angular CLI Builders." Tarun Gurang | Sciencx - Accessed . https://www.scien.cx/2021/11/03/introduction-to-angular-cli-builders/
IEEE
" » Introduction to Angular CLI Builders." Tarun Gurang | Sciencx [Online]. Available: https://www.scien.cx/2021/11/03/introduction-to-angular-cli-builders/. [Accessed: ]
rf:citation
» Introduction to Angular CLI Builders | Tarun Gurang | Sciencx | https://www.scien.cx/2021/11/03/introduction-to-angular-cli-builders/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.