One-Line Angular Schematics — The practical guide
There are lots of articles about Angular Schematics and powerful is. But we need to simplify it!
I decided to find a way to create components faster by a template, so I started to study Schematics. After some days studying and debugging the Angular and Material code I can show you a way to make it using just one line of code.
The Goal
Using a template to create a component with no options and other files manipulations.
It just requires to apply the name to the component to the template and move it to the correct path. The files manipulation to include the component in the module is a feature not required to the schematics. So you can import, export set as entry component by yourself.
The Barebones
To help you, I created a repository with the examples.
But let’s create an Angular project, install the dependencies and make some configurations.
$ ng new [project-name]$ yarn add -D @schematics/angular @angular-devkit/schematics-cli
To make the configurations we need to create the schematics project:
$ yarn schematics blank custom-schematics
To make the job easy we can add a script at package.json to link the schematics to the main project.
"schematics:link": "yarn --cwd custom-schematics/ link ; yarn link \"custom-schematics\""
The templates
The templates need to be inside of the file directory of the schematic you want to use.
Here the example of the template for a component.
The Strategy
This strategy you will write some code, but this code will be totally reusable. To help us with this code we need to install the package schematics-utilities
inside the custom-schematics project.
$ cd custom-schematics ; y add schematics-utilities
And we will create the helper files
The setupOptions will manage the properties for us. It will get the correct project name, path, module.
The buildTemplateSource will get info the from setupOptions, apply to the templates and move to correct path.
And join these methods to just one
Implement the Schematic
The schematics to fistStrategy will use only the buildTemplates method we created at utils directory to make all logic to generate our code.
Tomas Trajan wrote a great detailed explanation about schematics, you can check it: