Załóżmy, że chcemy generować własny komponent z jakimś początkowym stanem, spełniającym nasze wymagania. Logika podpowiada, że nie ma sensu dublować całej logiki komendy „ng g component somePath/someName”, prawda?
W tym celu, nauczymy się jak robić kombinacje z istniejącymi Schematics!
Zaczynamy od nowego Schematic, który będzie odpowiadał za wygenerowanie komponentu z dyrektywą *ngFor w templatce:
1 |
schematics blank list-component |
Schema.json kopiujemy z Schematics dla komponentu:
https://github.com/angular/angular-cli/blob/master/packages/schematics/angular/component/schema.json
Idea jest taka – skorzystajmy ze @angular/schematics:component, ale podrzućmy naszą templatkę.
Rule factory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { apply, chain, externalSchematic, mergeWith, move, Rule, SchematicContext, template, Tree, url } from '@angular-devkit/schematics'; import { normalize, strings } from '@angular-devkit/core'; import { setupOptions } from '../utils/setup-options'; export function listComponent(options: any): Rule { return (tree: Tree, context: SchematicContext) => { setupOptions(tree, options); const movePath = (options.flat) ? normalize(options.path) : normalize(options.path + '/' + strings.dasherize(options.name)); const templateSource = apply(url('./files'), [ template({ ...strings, ...options, }), move(movePath), ]); return chain([ externalSchematic('@schematics/angular', 'component', options), mergeWith(templateSource), ])(tree, context); }; } |
Cała magia dzieje się w funkcji externalSchematics – tutaj podajemy nazwę kompletu schemactics, następnie nazwę konkretnego schematic i przekazujemy options.
Następnie mergujemy z naszą templatką. Korzystamy również z funkcji chain, która wykonuje konkatencję Rules – jako parametr przyjmuje tablicę Rule[]) i zwraca jeden Rule.
Kod:
https://github.com/tomasznastaly/angular-schematics-tutorial/pull/11/files17