Advanced Angular CLI (Schematics, Builders)
The Angular CLI is built on two powerful concepts: schematics (code generators) and builders (build task executors). Understanding how they work allows you to extend and automate your workflow.
Schematics
Section titled “Schematics”A schematic is a code generator that can create or modify files in a project. For example, ng generate component uses a schematic.
Creating a simple schematic:
- Install tools:
npm install -g @angular-devkit/schematics-cli- Create a schematic collection:
schematics blank --name=my-collection cd my-collection- Modify the default schematic (
src/my-collection/index.ts):
import { Rule, Tree, SchematicContext } from "@angular-devkit/schematics";
export function myCollection(_options: any): Rule { return (tree: Tree, _context: SchematicContext) => { tree.create("hello.txt", "Hello from my schematic!"); return tree; };}- Build and run locally:
npm run build schematics .:my-collectionExplanation:
- A schematic must export a function returning a
Rule. - The
Rulereceives aTree(virtual file system) and can create/modify files. - The
schematicscommand allows testing without integrating into an Angular project.
Builders
Section titled “Builders”A builder is a function that executes a task (build, test, etc.) and can be configured in angular.json.
Creating a simple builder:
- Generate a builder project:
ng new my-builder --create-application=false cd my-builder- Create a builder file (
src/my-builder/index.ts):
import { BuilderContext, BuilderOutput, createBuilder } from "@angular-devkit/architect";import { JsonObject } from "@angular-devkit/core";
interface Options extends JsonObject { message: string;}
export default createBuilder((options: Options, context: BuilderContext): Promise<BuilderOutput> => { context.logger.info(`Message: ${options.message}`); return Promise.resolve({ success: true });});- Declare the builder in
builders.json:
{ "builders": { "my-builder": { "implementation": "./src/my-builder/index.js", "schema": "./src/my-builder/schema.json", "description": "An example builder" } }}- Configure the builder in an app’s
angular.json:
"projects": { "my-app": { "architect": { "my-builder": { "builder": "./my-builder:my-builder", "options": { "message": "Hello" } } } } }- Run the builder:
ng run my-app:my-builderExplanation:
- A builder receives typed options and a context for logging.
- It must be declared in a
builders.jsonand referenced via a local or published package. - Builders are used by the Angular CLI to customize the build process.