Smart Systems for Home

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

Add Schematics to Angular Library: Setup & Updates

· 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 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

  1. Create the schematics folder structure – Inside your library project folder (e.g., projects/my-lib), create a schematics directory. Within it, create a subfolder for each schematic you plan to add, like my-schematic. Each schematic folder will contain a schema.json (for options), a schema.ts (TypeScript interface for options), and a index.ts (the factory function).
  2. Define the schematic collection – Create a collection.json file in the schematics folder. 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"
        }
      }
    }
    The factory path points to the exported function in index.ts.
  3. Create the schema files – In schematics/my-schematic/, create schema.json to 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 create schema.ts with a matching interface:
    export interface MySchematicOptions {
      name: string;
    }
  4. Write the schematic factory – In index.ts, export a function that returns a Rule. Use the @angular-devkit/schematics API 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;
      };
    }
    Use tree.create, tree.overwrite, or tree.read to manipulate files. For more complex changes, consider using @schematics/update or the @angular-devkit/schematics utilities like apply and template.
  5. Compile the schematics – Schematics are written in TypeScript but must be compiled to JavaScript before the CLI can use them. Add a tsconfig.schematics.json in 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 using tsc -p tsconfig.schematics.json. You can add this to your build script in package.json.
  6. Update the library's package.json – In the library's package.json (under projects/my-lib), add a schematics key pointing to the compiled collection file:
    "schematics": "./schematics/collection.json"
    Also ensure the files array includes the schematics folder so they get published:
    "files": [
      "**/*",
      "schematics/**/*"
    ]
  7. 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 that dist/my-lib/schematics/collection.json exists.
  8. Test the schematic locally – In a separate test application, add the library using npm link or by referencing the dist path. Then run ng generate my-lib:my-schematic --name=test to see if it works. Debug any errors by checking the console output.
  9. 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.
  10. Publish the library – When ready, publish to npm. The schematics will be included if the files array is correct. Users can then run ng add my-lib or ng 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 tsc before publishing.
  • Incorrect factory path – The factory in collection.json must 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.json is not referenced or is malformed, the CLI will throw an error. Validate the JSON and ensure the schema property 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 Tree API to avoid breaking on different user setups.

Tips

  • Use the @schematics/angular utility functions (like addModuleImportToModule) to modify Angular modules safely.
  • Test your schematics with a dry-run using --dry-run flag 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.json so users know what they do.
  • Use @angular-devkit/core's strings utilities 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 factory path in collection.json and ensure the schematics were built.
  • "Schema validation failed" – Your schema.json might have invalid properties or missing required fields. Double-check the JSON structure and the TypeScript interface.
  • CLI says "Collection cannot be resolved" – The schematics key 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 tree operations. Ensure you're using tree.create for new files and tree.overwrite for 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.