Angular Schematics: Package with a Library
In this article
This guide walks you through creating custom Angular schematics and packaging them alongside an Angular library so that when someone installs your library, they can run a schematic (for example, ng generate my-lib:my-schematic) to scaffold components, services, or configurations. You'll learn the file structure, the build setup, and the packaging steps needed to ship schematics that work in real Angular CLI projects.
What You'll Need
- Node.js (v18 or later recommended) and npm installed.
- Angular CLI installed globally (
npm install -g @angular/cli). - Basic familiarity with TypeScript and Angular project structure.
- A text editor or IDE of your choice.
Step-by-Step
- Create a new Angular workspace and library
Runng new my-workspace --no-create-applicationto create a workspace without a default app. Then generate a library inside it:ng generate library my-lib. This creates aprojects/my-libfolder with the library's source files. - Add a schematics folder to the library
Navigate toprojects/my-liband create a folder namedschematics. Inside it, create subfolders for each schematic you plan to provide. For this guide, we'll create one calledmy-schematic. - Create the schematic collection file
Inprojects/my-lib/schematics, create a file namedcollection.json. This is the manifest that tells the Angular CLI which schematics are available. A minimal collection looks like:{ "$schema": "../../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "my-schematic": { "description": "A custom schematic.", "factory": "./my-schematic/index#mySchematic", "schema": "./my-schematic/schema.json" } } }Thefactorypoints to a TypeScript file that exports a function, andschemadefines the options the user can pass. - Define the schema for options
Insideschematics/my-schematic, createschema.jsonto describe the options. For example, to accept anameoption:{ "$schema": "http://json-schema.org/schema", "id": "MySchematicSchema", "title": "My Schematic", "type": "object", "properties": { "name": { "type": "string", "description": "The name of the generated item.", "x-prompt": "What name?" } }, "required": ["name"] }Also create a TypeScript interfaceschema.tsthat matches this shape, e.g.,export interface MySchematicOptions { name: string; }. - Write the schematic factory function
Createindex.tsin the same folder. This function receives the options and returns aRulethat modifies the tree. A simple example that creates a file:import { Rule, Tree } from '@angular-devkit/schematics'; import { MySchematicOptions } from './schema'; export function mySchematic(options: MySchematicOptions): Rule { return (tree: Tree) => { tree.create(`my-${options.name}.txt`, `Hello ${options.name}`); return tree; }; }For more complex tasks, you can use@schematics/angularutilities to modify components, modules, etc. - Compile schematics to JavaScript
Schematics must be shipped as JavaScript, not TypeScript. Add a separatetsconfig.schematics.jsonin the library root to compile theschematicsfolder to CommonJS. Example:{ "compilerOptions": { "baseUrl": ".", "declaration": true, "module": "commonjs", "moduleResolution": "node", "outDir": "../../dist/my-lib/schematics", "rootDir": "./schematics", "target": "es2015" }, "include": ["schematics/**/*.ts"] }Then add a script in the rootpackage.json:"build:schematics": "tsc -p projects/my-lib/tsconfig.schematics.json". - Copy JSON files to the output
The compiled JavaScript won't copycollection.jsonandschema.jsonautomatically. Use a tool likecpxor a simple Node script to copy them. Installcpxas a dev dependency and add to the build script:cpx \"projects/my-lib/schematics/**/*.json\" dist/my-lib/schematics. - Update the library's package.json
Inprojects/my-lib/package.json, add aschematicsfield pointing to the collection file:"schematics": "./schematics/collection.json"
Also ensure thefilesarray includes the schematics folder if you use one (default Angular library package.json doesn't have a files field, but if you add one, include"schematics"). - Build the library and schematics together
Modify the rootpackage.jsonscripts to run both builds. For example:"build:lib": "ng build my-lib", "build:schematics": "tsc -p projects/my-lib/tsconfig.schematics.json && cpx \"projects/my-lib/schematics/**/*.json\" dist/my-lib/schematics", "build": "npm run build:lib && npm run build:schematics"
Runnpm run buildto produce the final package indist/my-lib. - Test locally
Create a separate Angular app (e.g.,ng new test-app). In that app, add your built library usingnpm install ../my-workspace/dist/my-lib(or useng addif you set that up). Then runng generate my-lib:my-schematic --name=test. If everything works, you'll see the generated file. - Publish the package
When ready, runnpm publishfrom thedist/my-libfolder. Ensure the package includes theschematicsfolder and theschematicsfield in its package.json.
Common Mistakes
- Forgetting to compile schematics: Shipping TypeScript files directly will break because the CLI expects JavaScript.
- Not copying JSON files: The
collection.jsonandschema.jsonare not compiled by tsc; they must be copied manually. - Wrong path in collection.json: The factory path must be relative to the
collection.jsonlocation and point to the compiled JS file (e.g.,./my-schematic/indexnot./my-schematic/index.ts). - Missing
schematicsfield in package.json: Without it, the CLI won't know where the collection is. - Using ES modules: Schematics must be CommonJS; using ES modules will cause import errors.
Tips
- Use
@schematics/angularutilities (likeapply,mergeWith,template) to create files from templates with variables. - Test your schematics with
ng g my-lib:my-schematic --dry-runto see what would be created without actually writing files. - Add a
ng-addschematic to your collection to allow users to runng add my-libto install the library and run setup code. - Keep schematics small and focused; they are code, so maintain them with unit tests if possible.
Troubleshooting
- Schematic not found: Check that the
schematicsfield in package.json points to the correct path and thatcollection.jsonexists in the published package. - Factory not exported: Ensure your
index.tsexports the function with the exact name referenced incollection.json(e.g.,export function mySchematic). - Cannot find module './schema': This usually means the compiled JS isn't in the same folder. Rebuild and check the
distfolder structure. - Schema validation errors: If the user passes options that don't match the schema, the CLI will error. Make sure
schema.jsonis valid JSON and that required properties are listed. - CLI uses old version of schematics: Clear npm cache and reinstall the library; sometimes the CLI caches the old package.
Frequently Asked Questions
Can I use schematics with a regular Angular app (not a library)?
Yes, you can create schematics in any Angular project, but packaging them with a library is a common way to distribute them. The steps are the same; just place the schematics folder in the project root and adjust paths.
Do schematics need to be compiled with the same TypeScript version as the library?
Not necessarily, but it's safer to use a compatible version. The schematics compile to JavaScript, so the TypeScript version mainly affects the output syntax. Use the same version as your Angular CLI to avoid surprises.
How do I add a schematic that modifies an existing file?
Use the Tree API to read, update, and write files. For example, to add an import to a module, read the file content, modify the string, and call tree.overwrite.
Can I use external libraries inside my schematic?
Yes, but they must be dependencies of the library package. The schematic runs in the user's environment, so any runtime dependencies must be listed in the library's dependencies (not devDependencies) in package.json.
How do I debug my schematic?
Use the --debug flag with ng generate to see the tree changes. You can also add console.log statements in your factory function; they'll show up in the terminal.
Is it possible to have multiple schematics in one collection?
Yes, just add multiple entries in collection.json, each with its own factory and schema. Users can call them individually, e.g., ng g my-lib:schematic-a and ng g my-lib:schematic-b.