×

iFour Logo

Introduction to Angular CLI Builders

Kapil Panchal - April 01, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
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 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.

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


1.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(
  async (options: Options, context: BuilderContext): Promise => {

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 };

  });

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.

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 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: 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. 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. 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): builder. When running this target, the name of the builder to use is of the form packageName:builderName. options. While running this target, a default set of options is used. 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. BuilderContext BuilderOutput createBuilder Looking for Genuine AngularJS Development Company ? Enquire Today. See here 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 1.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( async (options: Options, context: BuilderContext): Promise => { 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 }; }); 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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...

Power Apps Integration Challenges: Expert Insights & Solutions
Power Apps Integration Challenges: Expert Insights & Solutions

Power Apps Integration Challenges: Insights from 11 Experts Microsoft Power Apps has caught great hype in recent days. Why? because it helps you build apps 50% faster, saves 250+...