← Back to Angular, page 7

angular-0137 · Hard senior

What are Angular schematics, and how would you write one that generates a feature or supports ng add and ng update?

A schematic is a function that receives a virtual file system Tree and a context, and returns a modified Tree. Collections list schematics in collection.json. ng generate runs one, ng add runs the add schematic of a package, and ng update runs migration schematics. They let teams enforce structure and automate code changes.

Full answer

Schematics are the code generators and transformers behind the CLI. ng generate component runs a schematic. Teams write their own to create features in a standard shape, to install libraries, and to migrate code.

Core ideas:

  • A schematic is a rule: a function (tree: Tree, context: SchematicContext) => Tree | Observable<Tree> | Rule. The Tree is an in-memory copy of the project's files. Changes are only written to disk when the whole schematic succeeds, so a failure leaves nothing half done. A dry run (--dry-run) shows the changes.
  • Utilities compose rules: apply(url('./files'), [template({...}), move(path)]) reads template files (names like __name@dasherize__.component.ts.template), replaces placeholders, and mergeWith adds them. chain([...]) runs rules in order.
  • A collection.json maps schematic names to factory functions and a schema.json that describes options and prompts (name, project, path). Angular's @schematics/angular utilities help find the default project and path, and ts-morph or the TypeScript API edits existing code safely.

Three kinds:

  1. Generate: ng generate my-lib:feature orders creates files from templates.
  2. ng add: the package declares "ng-add": { "save": "dependencies" } and a schematic named ng-add that edits angular.json, adds providers to the app config, and installs peer packages.
  3. ng update: package.json has ng-update with migrations pointing to a migrations.json. Each migration has a version and a function that edits code for breaking changes, so users get automated upgrades.

Practical advice:

  • Keep templates small and close to real code, and keep a sample project to test against.
  • Test with SchematicTestRunner from @angular-devkit/schematics/testing, using a virtual tree.
  • Edit code with AST tools, not regular expressions.
  • Make schematics idempotent where possible (running twice does not break the project).
  • Nx generators serve the same role in Nx workspaces.
typescript
// file: feature/index.ts
import { Rule, SchematicContext, Tree, apply, chain, mergeWith, move, strings, template, url } from '@angular-devkit/schematics';

interface FeatureOptions {
  name: string;
  path: string;
}

export function feature(options: FeatureOptions): Rule {
  return (tree: Tree, context: SchematicContext) => {
    context.logger.info(`Creating feature ${options.name}`);
    const source = apply(url('./files'), [
      template({ ...strings, ...options }),
      move(`${options.path}/${strings.dasherize(options.name)}`),
    ]);
    return chain([mergeWith(source)])(tree, context);
  };
}

// file: collection.json
{
  "schematics": {
    "feature": {
      "description": "Creates a feature folder",
      "factory": "./feature/index#feature",
      "schema": "./feature/schema.json"
    },
    "ng-add": {
      "description": "Adds the library to a project",
      "factory": "./ng-add/index#ngAdd"
    }
  }
}

Angular 20.3 with `@angular-devkit/schematics` 20, type-checked. The schematic was not run through the CLI or the test runner here.

Key points

  • A schematic is a rule that transforms a virtual `Tree`, and changes apply only if it succeeds.
  • `collection.json` and `schema.json` register schematics and describe options.
  • Generate, `ng add` and `ng update` migrations are the three uses.
  • Test with `SchematicTestRunner`. Use AST tools. Keep schematics idempotent.

Common mistakes

  • Editing source files with regular expressions.
  • Writing schematics that cannot run twice safely.
  • Not testing against a sample workspace.

Follow-ups

  • How would you add a provider to `app.config.ts` from a schematic?
  • How does `ng update` know which migrations to run?
  • When would you choose an Nx generator?

Tips

  • Explain the virtual Tree and why it is safe.
  • Name the three uses.
  • Mention testing and AST editing.

Evaluation rubric

  • Explains Tree, rules and collections.
  • Covers generate, add, and update schematics.
  • Gives testing and safety advice.