Share
Embed
schematics-wdc-19
Slides of the Dev-session about Angular shematics: https://www.web-developer-conference.de/programm/#/talk/schematics-codegenerierung-nach-mas
Gregor Woiwode
October 14, 2019
Transcript
73 slides
-
Agenda ▪ What is a schematic? ▪ Dive into schematic
projects ▪ Rules ▪ Templates ▪ ng-add ▪ ng-update -
What is a Schematic? ▪ API to enhance Angular CLI
▪ Adds additional commands. -
When do we need Schematics? ▪ Scaffold files to match
Coding Guidelines ▪ Automatically migrate breaking changes introduced by our own libraries ▪ Simplify setup of 3-party-libraries -
What benefits bring Schematics? ▪ ⏱ Saves time when ➝
solving recurring developer tasks ➝ setting up 3-party-libraries ➝ migrating to newer library versions ➝ sharing project wide coding guidelines -
Project structure ▪ Similar to ng new ▪ Everything you
need in one place -
Schematic source ▪ Each schematic lives in its own directory.
▪ Tests are generated automatically. -
collection.json ▪ Schematics are described in JSON. ▪ Contains ➝
command name ➝ documentation -
package.json Register a collection { ... "author": "", "license": "MIT",
"schematics": "./src/collection.json" } -
Define a collection collection.json { "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "schematic-a":
{ ... }, "schematic-b": { ... }, "schematic-c": { ... }, "schematic-d": { ... } } } -
Define a collection collection.json ... "schematic-a": { "aliases": ["a"], "description":
"Short description", "factory": "./schematic-a/index#methodName", "schema": "./schematic-a/schema.json", "private": false|true } -
Define a schema schematic-a/schema.json { "$schema": "http://json-schema.org/schema", "id": "schmatic-a", "title":
"schematic title", "type": "object", "description": "schematic description", "properties": { ... }, "required": ["name"] } -
Schematic parameters schematic-a/schema.json { "properties": { "yourProperty": { "type": "string",
"description": "The name of the Component.", "default": "some default", "x-prompt": "What name would you like to use for the Component?" } } } -
Schematic parameters schematic-a/schema.json { "properties": { "yourProperty": { "type": "string",
"description": "Short description", "$default": { "$source": "argv", "index": 0 }, "x-prompt": "What name would you like to use for the Component?" } } } -
Define a factory schematic-a/index.ts import { HostTree } from '@angular-devkit/schematics';
export function factory(): Rule { return (tree: HostTree) => { return tree; }; } -
Define a factory taking parameters schematic-a/index.ts import { HostTree }
from '@angular-devkit/schematics'; export function factory(options: any): Rule { return (tree: HostTree) => { return tree; }; } Properties defined in schema.json -
Relation between collection & schematic index.ts import { Observable }
from 'rxjs'; const helloWorld$ = new Observable( function subscribe(observer) { observer.next('Hello'); observer.next('World'); observer.complete(); } ); collection.json "schematic-a": { "aliases": ["f"], "description": "...", "factory": ".../index#factory", "schema": "..../schema.json", } export function factory(): Rule { return (tree: HostTree) => { return tree; }; } -
HostTree, Tree ▪ Tree → Staging area for changes ▪
Contains ➝ the original file system ➝ a list of changes to apply to tree ➝ Virtual representation of every file in the workspace ▪ Tree is an interface ▪ HostTree implements Tree interface ▪ Provides API for work with file system and changes -
create() HostTree API Example import { Tree } from '@angular-devkit/schematics';
tree.create(path: string, content: Buffer | string) // Example tree.create('./welcome.txt', 'Welcome to WDC 2018!'); Filename or/with path to file Content to be inserted in the file -
exists() HostTree API Example import { Tree } from '@angular-devkit/schematics';
tree.exists(path: string): boolean // Example if (tree.exists('./welcome.txt')) { // do something if file existing } Filename or/with path to file -
overwrite() HostTree API Example import { Tree } from '@angular-devkit/schematics';
tree.overwrite(path: string, content: Buffer | string) // Example tree.overwrite('./welcome.txt', 'Welcome to WDC 2019!'); Path to the file to be overwritten Overwrite with new content -
beginUpdate() and commitUpdate() HostTree API Example import { Tree }
from '@angular-devkit/schematics'; tree.overwrite(path: string, content: Buffer | string) // Example tree.overwrite('./welcome.txt', 'Welcome to WDC 2019!'); Path to the file to be overwritten Overwrite with new content -
Context ▪ Each schematic runs in a context ▪ Provides
access to utility functions and metadata ▪ Including a logging API → Helps with debugging ▪ Defines merge strategy -
Logging API SchematicContext API Example import { SchematicContext } from
'@angular-devkit/schematics'; return (tree: Tree, context: SchematicContext) => { context.logger.info('Hello WDC 2019!'); context.logger.error('Error!'); context.logger.warn('Warning!'); ... return tree; } Define schematic context Write warning message to console -
Tasks ▪ SchematicContext object allow to run tasks ▪ Usage:
context.addTask() ▪ e.g.: NodePackageInstallTask() ▪ e.g.: RunSchematicTask() -
Templates <TEMPLATE> Source factory ng g lib:shecmatic \ --name 'Hi
WDC' \ --spec false \ --flat true -
Template Templates @Component({ selector: <%= selector %>, templateUrl: './<%= kebabCase(name)
%>.page.html', }) export class <%= upperFirst(camelCase(name)) %>Page implements OnInit { <% if(routePath) { %>private route: ActivatedRoute <% } %> } -
File operators ▪ Allow loading and transforming file templates. ▪
Create own virtual file streams. ▪ Turn virtual file streams into reality by merging them into host tree. -
API Demo Load, transform, merge const templates = apply( url('./files'),
[ applyTemplates({ ...options, ...strings }) ]); Create a virtual file tree -
API Demo Load, transform, merge const templates = apply( url('./files'),
[ applyTemplates({ ...options, ...strings }) ]); Load templates from path. -
Factory Load & transform const templates = apply( url('./files'), [
applyTemplates({ ...options, ...strings }) ]); Merge options and pipes into templates -
Merge into tree Factory export function component(options: ComponentOptions): Rule {
return (_host: HostTree) => { const templates = apply(url('./files'), [ applyTemplates({ ...options, ...strings }) ]); return chain([mergeWith(templates)]); }; } -
Factory Further operators apply(url('./files'), [ applyTemplates({ ...component, ...strings }), move(component.path),
forEach(entry => (tree.exists(entry.path) ? null : entry)) ]); -
ng-add ▪ Automatically add library to project ▪ Download and
install dependencies ▪ Invokes installation script -
collection.json Define ng-add collection ... "ng-add": { "aliases": ["install"], "description":
"Custom ng-add schematic", "factory": "./ng-add/index", "schema": "./ng-add/schema.json" } ... -
Relation between collection & schematic index.ts import { Observable }
from 'rxjs'; const helloWorld$ = new Observable( function subscribe(observer) { observer.next('Hello'); observer.next('World'); observer.complete(); } ); collection.json ... "ng-add": { "aliases": ["install"], "description": "...", "factory": "./ng-add/index", "schema": "./ng-add/schema.json" } export default function(options: any): Rule { return (tree: Tree,) => { // ... return tree; } } -
Helper tools ▪ Add node dependencies to package.json ▪ Interface
for node dependency ▪ Enum for node dependency types -
NodeDependency and NodeDependencyType dependencies.d.ts export interface NodeDependency { type: NodeDependencyType;
name: string; version: string; overwrite?: boolean; } dependencies.d.ts export enum NodeDependencyType { Default = "dependencies", Dev = "devDependencies", Peer = "peerDependencies", Optional = "optionalDependencies" } -
index.ts addPackageJsonDependency() import { addPackageJsonDependency, NodeDependency } from '@schematics/angular/utility/dependencies'; ...
function addPackageJsonDependencies(): Rule { return (tree: Tree, context: SchematicContext) => { const dependency: NodeDependency = { ... }; addPackageJsonDependency(tree, dependency); return tree; } } -
ng-update ▪ Automatically do migrations ▪ Apply fixes project wide
▪ Update specific packages -
migrations.json Define migration { "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "migration-v2": {
"version": "2.0.0", "description": "Add test file to component", "factory": "./ng-update/index#updateToV2" } } } -
Relation between migrations & schematic index.ts import { Observable }
from 'rxjs'; const helloWorld$ = new Observable( function subscribe(observer) { observer.next('Hello'); observer.next('World'); observer.complete(); } ); migrations.json ... "migration-v2": { "version": "2.0.0", "description": "...", "factory": ".../index#migration", } export function migration(): Rule { return (tree: HostTree) => { // ... return tree; }; } -
Resources ▪ https://mhartington.io/post/angular-schematics-and-dynamic-content/ ▪ https://medium.com/@tomastrajan/total-guide-to-custom-angular-schematics-5c50cf90cdb4 ▪ https://www.youtube.com/watch?v=bnhrLH3bOFo ▪ https://www.youtube.com/watch?v=ZKyz0lb0GjA ▪
https://unsplash.com ▪ https://flaticon.com -
Assets | Code hello-world.ts hello-world.ts import { Observable } from
'rxjs'; const helloWorld$ = new Observable( function subscribe(observer) { observer.next('Hello'); observer.next('World'); observer.complete(); } ); // ... const observer = { next: (value) => console.log(value), error: (err) => console.error(err), complete: () => console.log('done') }; const subscription = helloWorld$.subscribe(observer);