Creating Custom Schematics
Beyond the simple example, you can create reusable schematics that modify existing projects, add files, update configurations, etc.
Structure of a schematic collection
Section titled “Structure of a schematic collection”my-collection/ package.json collection.json src/ my-schematic/ files/ # Folders/files to copy (optional) __name@dasherize__.ts index.ts schema.json # Options schema schema.d.ts # TypeScript typingsCreating a schematic that adds a custom component
Section titled “Creating a schematic that adds a custom component”- Define the options schema (
src/my-schematic/schema.json):
{ "$schema": "http://json-schema.org/schema", "id": "MySchematicSchema", "title": "Options for my schematic", "type": "object", "properties": { "name": { "type": "string", "description": "The component name" } }, "required": ["name"]}- Create a template file (
src/my-schematic/files/__name@dasherize__.component.ts):
import { Component } from '@angular/core';
@Component({ selector: 'app-<%= dasherize(name) %>', template: `<h2><%= classify(name) %> Component</h2>` }) export class <%= classify(name) %>Component {}- Implement the rule (
src/my-schematic/index.ts):
import { Rule, SchematicContext, Tree, apply, url, template, move, chain } from "@angular-devkit/schematics";import { strings } from "@angular-devkit/core";
export function mySchematic(options: any): Rule { return (tree: Tree, context: SchematicContext) => { const templateSource = apply(url("./files"), [template({ ...strings, ...options }), move("src/app/components")]); return chain([templateSource])(tree, context); };}- Declare the schematic in
collection.json:
{ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "my-schematic": { "description": "Adds a custom component", "factory": "./src/my-schematic/index#mySchematic", "schema": "./src/my-schematic/schema.json" } }}- Test locally:
npm run build schematics .:my-schematic --name=testExplanation:
- Templates use EJS syntax (
<%= ... %>) and helpers likedasherize,classify.
applycombines a source (url) and rules (template,move).- The schematic can be run in any Angular project after installation.