Mamy już funkcję setupOptions, która zwraca nam odpowiednią ścieżkę i nazwę dla pliku. Zapewne zwróciłeś/aś uwagę, że korzystając z komendy:
1 |
ng generate component shared/directives/scroll |
to katalog „scroll” domyślnie zostanie utworzony, a dopiero w nim zostanie umieszczony plik scroll.directive.ts.
Natomiast jak użyjesz flagi –flat:
1 |
ng generate component shared/directives/scroll --flat |
to plik scroll.directive.ts powstanie od razu w katalogu directives.
Aby uzyskać takie zachowanie w Angular Schematics, musimy wzbogacić schematic o identyczną opcję –flat.
Zatem przechodzimy do pliku schema.json i dodajemy nową właściwość, którą będzie mógł podać użytkownik:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ "$schema": "http://json-schema.org/schema", "id": "simpleSchema", "title": "Creates a httpService Schematic.", "type": "object", "properties": { "path": {...}, "name": {...}, "project": {...}, "flat": { "type": "boolean", "description": "When true, creates the new files at the top level of the current project.", "default": false } } } |
Następnie w Rule Factory (index.ts), wołamy funkcję setupOptions i sprawdzamy czy flaga flat jest równa true:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; import { normalize, strings } from '@angular-devkit/core'; import { setupOptions } from '../utils/setup-options'; import { HttpServiceOptions } from './schema'; // You don't have to export the function as default. You can also have more than one rule factory // per file. export function httpService(options: HttpServiceOptions): Rule { return (tree: Tree, _context: SchematicContext) => { // przygotowujemy path i name setupOptions(tree, options); // movePath to miejsce gdzie ma trafić plik w projekcie, taka ścieżka musi być systemowa, dlatego używamy utila normalize const movePath = options.flat ? // czy plik nie ma mieć swojego katalogu ? normalize(options.path || '') : // jak nie ma mieć, to mamy już ścieżkę normalize(options.path + '/' + strings.dasherize(options.name)); // jak ma mieć katalog swój, to doklej jeszcze nazwę return rule(tree, _context); }; } |
Mamy docelową ścieżkę, a dzięki utilsowi normalize, jest ona systemowa. Jesteśmy już co raz bliżej stworzenia templatki!
Kod:
https://github.com/tomasznastaly/angular-schematics-tutorial/pull/4/files