Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Angular Schematics: Package with a Library

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. Create a new Angular workspace and library
    Run ng new my-workspace --no-create-application to create a workspace without a default app. Then generate a library inside it: ng generate library my-lib. This creates a projects/my-lib folder with the library's source files.
  2. Add a schematics folder to the library
    Navigate to projects/my-lib and create a folder named schematics. Inside it, create subfolders for each schematic you plan to provide. For this guide, we'll create one called my-schematic.
  3. Create the schematic collection file
    In projects/my-lib/schematics, create a file named collection.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"
        }
      }
    }
    The factory points to a TypeScript file that exports a function, and schema defines the options the user can pass.
  4. Define the schema for options
    Inside schematics/my-schematic, create schema.json to describe the options. For example, to accept a name option:
    {
      "$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 interface schema.ts that matches this shape, e.g., export interface MySchematicOptions { name: string; }.
  5. Write the schematic factory function
    Create index.ts in the same folder. This function receives the options and returns a Rule that 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/angular utilities to modify components, modules, etc.
  6. Compile schematics to JavaScript
    Schematics must be shipped as JavaScript, not TypeScript. Add a separate tsconfig.schematics.json in the library root to compile the schematics folder 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 root package.json: "build:schematics": "tsc -p projects/my-lib/tsconfig.schematics.json".
  7. Copy JSON files to the output
    The compiled JavaScript won't copy collection.json and schema.json automatically. Use a tool like cpx or a simple Node script to copy them. Install cpx as a dev dependency and add to the build script: cpx \"projects/my-lib/schematics/**/*.json\" dist/my-lib/schematics.
  8. Update the library's package.json
    In projects/my-lib/package.json, add a schematics field pointing to the collection file:
    "schematics": "./schematics/collection.json"
    Also ensure the files array 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").
  9. Build the library and schematics together
    Modify the root package.json scripts 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"
    Run npm run build to produce the final package in dist/my-lib.
  10. Test locally
    Create a separate Angular app (e.g., ng new test-app). In that app, add your built library using npm install ../my-workspace/dist/my-lib (or use ng add if you set that up). Then run ng generate my-lib:my-schematic --name=test. If everything works, you'll see the generated file.
  11. Publish the package
    When ready, run npm publish from the dist/my-lib folder. Ensure the package includes the schematics folder and the schematics field 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.json and schema.json are not compiled by tsc; they must be copied manually.
  • Wrong path in collection.json: The factory path must be relative to the collection.json location and point to the compiled JS file (e.g., ./my-schematic/index not ./my-schematic/index.ts).
  • Missing schematics field 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/angular utilities (like apply, mergeWith, template) to create files from templates with variables.
  • Test your schematics with ng g my-lib:my-schematic --dry-run to see what would be created without actually writing files.
  • Add a ng-add schematic to your collection to allow users to run ng add my-lib to 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 schematics field in package.json points to the correct path and that collection.json exists in the published package.
  • Factory not exported: Ensure your index.ts exports the function with the exact name referenced in collection.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 dist folder structure.
  • Schema validation errors: If the user passes options that don't match the schema, the CLI will error. Make sure schema.json is 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.