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. TheTreeis 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, andmergeWithadds them.chain([...])runs rules in order. - A
collection.jsonmaps schematic names to factory functions and aschema.jsonthat describes options and prompts (name, project, path). Angular's@schematics/angularutilities help find the default project and path, andts-morphor the TypeScript API edits existing code safely.
Three kinds:
- Generate:
ng generate my-lib:feature orderscreates files from templates. ng add: the package declares"ng-add": { "save": "dependencies" }and a schematic namedng-addthat editsangular.json, adds providers to the app config, and installs peer packages.ng update:package.jsonhasng-updatewithmigrationspointing to amigrations.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
SchematicTestRunnerfrom@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.