1 | # Schematics
|
2 |
|
3 | > A scaffolding library for the modern web.
|
4 |
|
5 | ## Description
|
6 |
|
7 | Schematics are generators that transform an existing filesystem. They can create files, refactor existing files, or move files around.
|
8 |
|
9 | What distinguishes Schematics from other generators, such as Yeoman or Yarn Create, is that schematics are purely descriptive; no changes are applied to the actual filesystem until everything is ready to be committed. There is no side effect, by design, in Schematics.
|
10 |
|
11 | # Glossary
|
12 |
|
13 | | Term | Description |
|
14 | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
15 | | **Schematics** | A generator that executes descriptive code without side effects on an existing file system. |
|
16 | | **Collection** | A list of schematics metadata. Schematics can be referred by name inside a collection. |
|
17 | | **Tool** | The code using the Schematics library. |
|
18 | | **Tree** | A staging area for changes, containing the original file system, and a list of changes to apply to it. |
|
19 | | **Rule** | A function that applies actions to a `Tree`. It returns a new `Tree` that will contain all transformations to be applied. |
|
20 | | **Source** | A function that creates an entirely new `Tree` from an empty filesystem. For example, a file source could read files from disk and create a Create Action for each of those. |
|
21 | | **Action** | An atomic operation to be validated and committed to a filesystem or a `Tree`. Actions are created by schematics. |
|
22 | | **Sink** | The final destination of all `Action`s. |
|
23 | | **Task** | A Task is a way to execute an external command or script in a schematic. A Task can be used to perform actions such as installing dependencies, running tests, or building a project. A Task is created by using the `SchematicContext` object and can be scheduled to run before or after the schematic `Tree` is applied. |
|
24 |
|
25 | # Tooling
|
26 |
|
27 | Schematics is a library, and does not work by itself. A [reference CLI](https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics.ts) is available on this repository, and is published on NPM at [@angular-devkit/schematics-cli](https://www.npmjs.com/package/@angular-devkit/schematics-cli). This document explains the library usage and the tooling API, but does not go into the tool implementation itself.
|
28 |
|
29 | The tooling is responsible for the following tasks:
|
30 |
|
31 | 1. Create the Schematic Engine, and pass in a Collection and Schematic loader.
|
32 | 1. Understand and respect the Schematics metadata and dependencies between collections. Schematics can refer to dependencies, and it's the responsibility of the tool to honor those dependencies. The reference CLI uses NPM packages for its collections.
|
33 | 1. Create the Options object. Options can be anything, but the schematics can specify a JSON Schema that should be respected. The reference CLI, for example, parses the arguments as a JSON object and validates it with the Schema specified by the collection.
|
34 | 1. Schematics provides some JSON Schema formats for validation that tooling should add. These validate paths, html selectors and app names. Please check the reference CLI for how these can be added.
|
35 | 1. Call the schematics with the original Tree. The tree should represent the initial state of the filesystem. The reference CLI uses the current directory for this.
|
36 | 1. Create a Sink and commit the result of the schematics to the Sink. Many sinks are provided by the library; FileSystemSink and DryRunSink are examples.
|
37 | 1. Output any logs propagated by the library, including debugging information.
|
38 |
|
39 | The tooling API is composed of the following pieces:
|
40 |
|
41 | ## Engine
|
42 |
|
43 | The `SchematicEngine` is responsible for loading and constructing `Collection`s and `Schematics`. When creating an engine, the tooling provides an `EngineHost` interface that understands how to create a `CollectionDescription` from a name, and how to create a `SchematicDescription`.
|
44 |
|
45 | # Schematics (Generators)
|
46 |
|
47 | Schematics are generators and part of a `Collection`.
|
48 |
|
49 | ## Collection
|
50 |
|
51 | A Collection is defined by a `collection.json` file (in the reference CLI). This JSON defines the following properties:
|
52 |
|
53 | | Prop Name | Type | Description |
|
54 | | ----------- | -------- | --------------------------- |
|
55 | | **name** | `string` | The name of the collection. |
|
56 | | **version** | `string` | Unused field. |
|
57 |
|
58 | ## Schematic
|
59 |
|
60 | # Operators, Sources and Rules
|
61 |
|
62 | A `Source` is a generator of a `Tree`; it creates an entirely new root tree from nothing. A `Rule` is a transformation from one `Tree` to another. A `Schematic` (at the root) is a `Rule` that is normally applied on the filesystem.
|
63 |
|
64 | ## Operators
|
65 |
|
66 | `FileOperator`s apply changes to a single `FileEntry` and return a new `FileEntry`. The result follows these rules:
|
67 |
|
68 | 1. If the `FileEntry` returned is null, a `DeleteAction` will be added to the action list.
|
69 | 1. If the path changed, a `RenameAction` will be added to the action list.
|
70 | 1. If the content changed, an `OverwriteAction` will be added to the action list.
|
71 |
|
72 | It is impossible to create files using a `FileOperator`.
|
73 |
|
74 | ## Provided Operators
|
75 |
|
76 | The Schematics library provides multiple `Operator` factories by default that cover basic use cases:
|
77 |
|
78 | | FileOperator | Description |
|
79 | | -------------------------------- | -------------------------------------------------------------------- |
|
80 | | `contentTemplate<T>(options: T)` | Apply a content template (see the [Templating](#templating) section) |
|
81 | | `pathTemplate<T>(options: T)` | Apply a path template (see the [Templating](#templating) section) |
|
82 |
|
83 | ## Provided Sources
|
84 |
|
85 | The Schematics library additionally provides multiple `Source` factories by default:
|
86 |
|
87 | | Source | Description |
|
88 | | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
89 | | `empty()` | Creates a source that returns an empty `Tree`. |
|
90 | | `source(tree: Tree)` | Creates a `Source` that returns the `Tree` passed in as argument. |
|
91 | | `url(url: string)` | Loads a list of files from the given URL and returns a `Tree` with the files as `CreateAction` applied to an empty `Tree`. |
|
92 | | `apply(source: Source, rules: Rule[])` | Apply a list of `Rule`s to a source, and return the resulting `Source`. |
|
93 |
|
94 | ## Provided Rules
|
95 |
|
96 | The schematics library also provides `Rule` factories by default:
|
97 |
|
98 | | Rule | Description |
|
99 | | ------------------------------------------- | -------------------------------------------------------------------------------------- |
|
100 | | `noop()` | Returns the input `Tree` as is. |
|
101 | | `chain(rules: Rule[])` | Returns a `Rule` that's the concatenation of other `Rule`s. |
|
102 | | `forEach(op: FileOperator)` | Returns a `Rule` that applies an operator to every file of the input `Tree`. |
|
103 | | `move(root: string)` | Moves all the files from the input to a subdirectory. |
|
104 | | `merge(other: Tree)` | Merge the input `Tree` with the other `Tree`. |
|
105 | | `contentTemplate<T>(options: T)` | Apply a content template (see the Template section) to the entire `Tree`. |
|
106 | | `pathTemplate<T>(options: T)` | Apply a path template (see the Template section) to the entire `Tree`. |
|
107 | | `template<T>(options: T)` | Apply both path and content templates (see the Template section) to the entire `Tree`. |
|
108 | | `filter(predicate: FilePredicate<boolean>)` | Returns the input `Tree` with files that do not pass the `FilePredicate`. |
|
109 |
|
110 | # Templating
|
111 |
|
112 | As referenced above, some functions are based upon a file templating system, which consists of path and content templating.
|
113 |
|
114 | The system operates on placeholders defined inside files or their paths as loaded in the `Tree` and fills these in as defined in the following, using values passed into the `Rule` which applies the templating (i.e. `template<T>(options: T)`).
|
115 |
|
116 | ## Path Templating
|
117 |
|
118 | | Placeholder | Description |
|
119 | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
120 | | `__variable__` | Replaced with the value of `variable`. |
|
121 | | `__variable@function__` | Replaced with the result of the call `function(variable)`. Can be chained to the left (`__variable@function1@function2__ ` etc). |
|
122 |
|
123 | ## Content Templating
|
124 |
|
125 | | Placeholder | Description |
|
126 | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
127 | | `<%= expression %>` | Replaced with the result of the call of the given expression. This only supports direct expressions, no structural (for/if/...) JavaScript. |
|
128 | | `<%- expression %>` | Same as above, but the value of the result will be escaped for HTML when inserted (i.e. replacing '<' with '\<') |
|
129 | | `<% inline code %>` | Inserts the given code into the template structure, allowing to insert structural JavaScript. |
|
130 | | `<%# text %>` | A comment, which gets entirely dropped. |
|
131 |
|
132 | # Examples
|
133 |
|
134 | ## Simple
|
135 |
|
136 | An example of a simple Schematics which creates a "hello world" file, using an option to determine its path:
|
137 |
|
138 | ```typescript
|
139 | import { Tree } from '@angular-devkit/schematics';
|
140 |
|
141 | export default function MySchematic(options: any) {
|
142 | return (tree: Tree) => {
|
143 | tree.create(options.path + '/hi', 'Hello world!');
|
144 | return tree;
|
145 | };
|
146 | }
|
147 | ```
|
148 |
|
149 | A few things from this example:
|
150 |
|
151 | 1. The function receives the list of options from the tooling.
|
152 | 1. It returns a [`Rule`](src/engine/interface.ts#L73), which is a transformation from a `Tree` to another `Tree`.
|
153 |
|
154 | ## Templating
|
155 |
|
156 | A simplified example of a Schematics which creates a file containing a new Class, using an option to determine its name:
|
157 |
|
158 | ```typescript
|
159 | // files/__name@dasherize__.ts
|
160 |
|
161 | export class <%= classify(name) %> {
|
162 | }
|
163 | ```
|
164 |
|
165 | ```typescript
|
166 | // index.ts
|
167 |
|
168 | import { strings } from '@angular-devkit/core';
|
169 | import {
|
170 | Rule,
|
171 | SchematicContext,
|
172 | SchematicsException,
|
173 | Tree,
|
174 | apply,
|
175 | branchAndMerge,
|
176 | mergeWith,
|
177 | template,
|
178 | url,
|
179 | } from '@angular-devkit/schematics';
|
180 | import { Schema as ClassOptions } from './schema';
|
181 |
|
182 | export default function (options: ClassOptions): Rule {
|
183 | return (tree: Tree, context: SchematicContext) => {
|
184 | if (!options.name) {
|
185 | throw new SchematicsException('Option (name) is required.');
|
186 | }
|
187 |
|
188 | const templateSource = apply(url('./files'), [
|
189 | template({
|
190 | ...strings,
|
191 | ...options,
|
192 | }),
|
193 | ]);
|
194 |
|
195 | return branchAndMerge(mergeWith(templateSource));
|
196 | };
|
197 | }
|
198 | ```
|
199 |
|
200 | Additional things from this example:
|
201 |
|
202 | 1. `strings` provides the used `dasherize` and `classify` functions, among others.
|
203 | 1. The files are on-disk in the same root directory as the `index.ts` and loaded into a `Tree`.
|
204 | 1. Then the `template` `Rule` fills in the specified templating placeholders. For this, it only knows about the variables and functions passed to it via the options-object.
|
205 | 1. Finally, the resulting `Tree`, containing the new file, is merged with the existing files of the project which the Schematic is run on.
|