Add Schematics to Angular Library: Setup & Updates
In this article
This guide walks you through adding schematics to an Angular library, covering both the initial setup and how to keep them updated as your library evolves. Schematics let you automate code generation and modification tasks—like adding a module or configuring a feature—directly from the Angular CLI. You'll need an existing Angular library workspace (created with ng new and ng generate library) and Node.js/npm installed.
What You'll Need
- An Angular workspace with at least one library project (e.g.,
my-lib) - Angular CLI version 12 or later (check with
ng version) - Node.js and npm (or yarn) installed
- Basic understanding of TypeScript and Angular project structure
Step-by-Step
- Create the schematics folder structure – Inside your library project folder (e.g.,
projects/my-lib), create aschematicsdirectory. Within it, create a subfolder for each schematic you plan to add, likemy-schematic. Each schematic folder will contain aschema.json(for options), aschema.ts(TypeScript interface for options), and aindex.ts(the factory function). - Define the schematic collection – Create a
collection.jsonfile in theschematicsfolder. This file tells the CLI what schematics are available. A minimal example:{ "$schema": "../../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "my-schematic": { "description": "Adds a feature to the library", "factory": "./my-schematic/index#mySchematic", "schema": "./my-schematic/schema.json" } } }Thefactorypath points to the exported function inindex.ts. - Create the schema files – In
schematics/my-schematic/, createschema.jsonto define user options. For example:{ "$schema": "http://json-schema.org/schema", "id": "MySchematicSchema", "title": "My Schematic", "type": "object", "properties": { "name": { "type": "string", "description": "The name of the feature" } }, "required": ["name"] }Then createschema.tswith a matching interface:export interface MySchematicOptions { name: string; } - Write the schematic factory – In
index.ts, export a function that returns aRule. Use the@angular-devkit/schematicsAPI to create or modify files. A simple example that creates a file:import { Rule, Tree, SchematicContext } from '@angular-devkit/schematics'; import { strings } from '@angular-devkit/core'; import { MySchematicOptions } from './schema'; export function mySchematic(options: MySchematicOptions): Rule { return (tree: Tree, _context: SchematicContext) => { const path = `src/${strings.dasherize(options.name)}.ts`; tree.create(path, `export class ${strings.classify(options.name)} {}`); return tree; }; }Usetree.create,tree.overwrite, ortree.readto manipulate files. For more complex changes, consider using@schematics/updateor the@angular-devkit/schematicsutilities likeapplyandtemplate. - Compile the schematics – Schematics are written in TypeScript but must be compiled to JavaScript before the CLI can use them. Add a
tsconfig.schematics.jsonin the library root:{ "compilerOptions": { "baseUrl": ".", "declaration": true, "module": "commonjs", "moduleResolution": "node", "outDir": "../../dist/my-lib/schematics", "rootDir": "./schematics", "target": "es2018", "types": ["node"] }, "include": ["schematics/**/*"] }Then compile usingtsc -p tsconfig.schematics.json. You can add this to your build script inpackage.json. - Update the library's package.json – In the library's
package.json(underprojects/my-lib), add aschematicskey pointing to the compiled collection file:"schematics": "./schematics/collection.json"
Also ensure thefilesarray includes the schematics folder so they get published:"files": [ "**/*", "schematics/**/*" ]
- Build the library – Run
ng build my-lib. This compiles the library and, if you've set up the schematics build, will also copy the compiled schematics to the dist folder. Verify thatdist/my-lib/schematics/collection.jsonexists. - Test the schematic locally – In a separate test application, add the library using
npm linkor by referencing the dist path. Then runng generate my-lib:my-schematic --name=testto see if it works. Debug any errors by checking the console output. - Update schematics when library changes – When you modify the library's public API or add new features, update the schematics accordingly. For example, if you add a new component, create or modify a schematic that generates the necessary imports. Recompile the schematics and rebuild the library. Always bump the library version to reflect the update.
- Publish the library – When ready, publish to npm. The schematics will be included if the
filesarray is correct. Users can then runng add my-liborng generate my-lib:my-schematic.
Common Mistakes
- Forgetting to compile schematics – Shipping TypeScript files directly will cause the CLI to fail because it expects JavaScript. Always run
tscbefore publishing. - Incorrect factory path – The
factoryincollection.jsonmust point to the compiled JS file (e.g.,./my-schematic/index.js), not the TS source. If you use a relative path, ensure it matches the output structure. - Missing schema file – If
schema.jsonis not referenced or is malformed, the CLI will throw an error. Validate the JSON and ensure theschemaproperty points to the correct file. - Not updating the package.json files array – If the schematics folder isn't included in
files, npm won't publish it, and users won't have access. - Using absolute paths in schematics – Always use relative paths or the
TreeAPI to avoid breaking on different user setups.
Tips
- Use the
@schematics/angularutility functions (likeaddModuleImportToModule) to modify Angular modules safely. - Test your schematics with a dry-run using
--dry-runflag to see what would change without applying it. - Keep your schematics small and focused. A single schematic should do one thing well.
- Document your schematics with clear descriptions in
collection.jsonso users know what they do. - Use
@angular-devkit/core'sstringsutilities to handle naming conventions (dasherize, classify, camelize).
Troubleshooting
- "Cannot find module './my-schematic/index'" – This usually means the compiled JS file is missing or the path is wrong. Check the
factorypath incollection.jsonand ensure the schematics were built. - "Schema validation failed" – Your
schema.jsonmight have invalid properties or missing required fields. Double-check the JSON structure and the TypeScript interface. - CLI says "Collection cannot be resolved" – The
schematicskey in package.json is missing or points to a non-existent file. Verify the path and that the file is included in the build. - Changes are not applied – If your schematic runs without error but doesn't modify files, check your
treeoperations. Ensure you're usingtree.createfor new files andtree.overwritefor existing ones. - Angular version mismatch – Schematics compiled with a newer version of Angular CLI might not work with older CLI versions. Keep your schematics compatible by using a broad range of peer dependencies.
Frequently Asked Questions
Do I need to write schematics in TypeScript?
Yes, but they must be compiled to JavaScript before publishing. The CLI executes JavaScript, so you can also write them directly in JS, but TypeScript is the standard for Angular projects.
Can I add schematics to an existing library without breaking it?
Yes, schematics are additive. You just need to create the schematics folder, compile, and update package.json. Existing functionality remains unchanged.
How do I test schematics locally?
Use npm link to link your library to a test project, then run ng generate commands. Alternatively, use ng add with a local path.
What is the difference between ng add and ng generate?
ng add runs the schematic defined in the library's ng-add entry, typically for initial setup. ng generate runs any schematic in the collection, allowing users to create features on demand.
How do I update schematics when my library changes?
Modify the schematic code to reflect new APIs or structures, recompile, rebuild the library, and publish a new version. Users will get the update when they upgrade the library.
Can schematics modify files outside the library?
Yes, schematics run in the user's project context, so they can modify any file in the workspace. Be careful to avoid overwriting user code without permission.