As productive as mother Earth! (Original š· by ) MarkusĀ Spiske Angular Schematics is a workflow tool for the modern webāāāofficial introduction article Quick Intro There are many articles on how to build your own Angular schematics but in this one weāre going to focus on using available schematics to the fullest! šŖ Most of the time we will be using which are provided in Angular CLI out of the box. @schematics/angular What are we going toĀ learn Use shortcuts, they are much faster and easier to type, duhhh š! Skip creation of an initial application Generate multiple applications and libs to promote code reuse Use schematics from different npm packages Set schematics defaults in file so that we donāt need to specify all the flags all the time angular.json Generate servicesāā vs flag (scoping to lazy-loaded modules) providedIn: 'root' --module Use to add libraries like Angular Material (or others) ng add Useful commands BONUS: Amazing code completion capabilities! BONUS+: FUN FACT: In the beginning all I had in mind was 6 distinct useful tips and see how it ended up. We have 7 main points and 2 bonuses š¤¦ But schematics just have so many cool features that there was no other way š 1. Use Shortcuts, They Are Much Faster!Ā šļø Most of the schematics commands in Angular CLI come with the shortcut version. For example, instead of we can simply write . ng generate service service-name ng g s service-name Less letters = lower probability of typos,Ā yaayš! Also, schematics used to be documented in the GitHub Wiki of the Angular CLI repository but this was improved. Official schematics documentation is now available as a part of together with the rest of the docs which is very convenient! Check them out to see all the available commands and their shortcut versions! angular.io 2. Skip Creation Of An Initial Application Angular CLI comes with great support for multiple apps and libraries in a single workspace. This feature can be easily missed because by default Angular CLI will generate new project with a default application directly in the project root in the folder. ./src/ Standard workspace generated using app-name ng new CLI will create new folder when we decide to add more libraries later during the development process. This will lead to a inconsistent code structure where original app doesnāt follow paths and conventions compared to the ones added later. projects This can be prevented by creating our new workspace with flag. ng new --createApplication=false What we get is an empty workspace. Then we can continue with the (or ). ng generate application our-first-app library our-first-library That way, all the code in the workspace will be located in the predictable location inside of folder! Great! ššš projects Minimal workspace generated by the Angular CLI with ng new cli-testāāāā createApplication=false 3. Generate Multiple Applications And Libraries To Promote CodeĀ Reuse As mentioned above, Angular CLI currently supports multiple apps and libraries in the single workspace (by default inside of the folder. projects/ The libraries and apps can be added by running and respectively. ng generate library library-name ng generate application app-name You can go with the multiple independent npm packages or monorepo, thatās up to your subjective preferences. Both have their distinctive advantages and disadvantages. The Angular CLI will generate libraries which will get their own file in the folder after they were built by . Such a library can be easily published to npm independently from the rest of the projects in the workspace. This supports multiple npm packages scenario out of the box package.json dist ng-packager On the other hand, tools like help us to implement similar structure in a monorepo fashion. Choose what works best for your use-case! @nrwl/nx How can we generate entities in different apps and libraries? Using schematics in a workspace with single app is very straight forward. Every call to will generate desired entity in the specified path inside of the one and only app. What would happen with multiple apps and libraries in a single workspace? ng generate The file contains the property which specifies which project will be implicitly assumed when executing any Angular CLI command. This is valid also for the things like or . angular.json defaultProject ng build ng test Example of a top level structure of angular.json file with one app and one libĀ project We can also specify flag as a part of these commands to make it run in a desired app or libraryā¦ The command will then look like this: --project <my-project-name> ng g c path/some-component --project some-app It might be worth it to change property in file when working mostly on a single app (or lib) to prevent unnecessary typing or create additional npm script in which will do that for us. For example, which we can then use like this . Note the npm pipe to pass in a sub-command. PRO TIP: defaultProject angular.json package.json "ng-my-lib": "ng run --project my-lib" npm run ng-my-lib -- test -- 4. Use schematics from 3rd party npmĀ packages Angular CLI comes with default set of schematics implemented in the npm which gives us ability to generate apps or components. @schematics/angular package The schematics itself are actually framework independent Many people, organizations and open source libraries already implemented and provided their own schematics in the npm registry for our use. A good example of this could be which ships its own schematics in the npm package. So how can we use this additional 3rd party schematics? NgRx state management library @ngrx/schematics Specify schematics package name in the generateĀ call This one is the most straight forward solution. Once we installed additional schematics package in our workspace we can simply call them using . Or to imagine it from a more practical angleāā ā¦ ng g <schematics-package-name>:<schematics-name> [...options] ng g @ngrx/schematics:action feature-name/entity-name --spec=true Comparison between using versus ng g schematics Run schematics without the help from AngularĀ CLI Schematics can be executed even without the help of Angular CLI. In that case we can just run . schematics @ngrx/schematics:action feature-name/entity-name How to make command available in our environment will be discussed in the section š schematics BONUS to get notified about the newest Angular blog posts and interesting frontendĀ stuff!š¤ Follow me on Twitter 5. Set schematics defaults in file so that we donāt need to specify all the flags all theĀ time angular.json Many of the schematics which we use to generate entities like components or services support vast amount of additional configuration flags. For example, with components we can set flag for and so that we have whole implementation inside of the component typescript file. --inlineStyle --inlineTemplate A single project usually contains many components so we would need to repeat these flags manually and quite often if we wanted to preserve unified code styleā¦ Luckily, Angular CLI has support for defining default values of the schematics options! Example of how to define workspace and project specific schematics defaults The default values are defined inside of the object and they are defined per individual schematic. Every schematic is defined by the package name and the respective schematic. schematics In the example above weāre providing defaults for the schematics from the package . component @schematics/angular This approach is great because it is flexible enough to allow us to specify defaults for multiple schematics packages like popular 3rd party , packages or even our own custom built . @nrwl/schematics @ngrx/schematics @some-org/schematics The object can be defined as a top level property and in that case defaults will be applied for the call flag. Project specific defaults can be configured too and will be activated only when using together with the flag. schematics ng g WITHOUT --project schematics ng g --project some-project Overriding of the default schematics collection Some schematics collections (like ) enable us to call original Angular CLI schematics (like or ) next to all the new schematics they are bringing to the table. ngrx component service In that case we can set such a collection as a default Angular CLI schematics collection using . The property will be added into file. ng config cli.defaultCollection <schematics-package> defaultCollection angular.json Setting default schematics collection in file will enable us to call provided schematics without the need to specify their package name in every call angular.json ng g Setting default collection enables us to execute schematics from that collection without the need to specify the schematics package name in the call. That way we can call instead of which is great! ng g action feature/action-name ng g @ngrx/schematics:action feature/action-name 6. Generate servicesāā vs flag (scoping to lazy-loaded modules) providedIn: 'root' --module Service generation has changed and the services generated by Angular CLI 6+ use new syntax by default. providedIn: 'root' Service generated using ng generate service some/path/feature Such a service doesnāt have to be specified in array of any which is nice convenience. Even better, library services provided in the root will be tree-shaken automatically if they were not explicitly imported by the consumer app! providers: [] @NgModule This is great improvement compared to previous dependency injection style using array when all the provided services would always end up in the bundle regardless of whether they were used at all! providers: [] Providing service using the old style has still its place when we want to get unique instance of the service per created component or when we want to scope service to lazy loaded module. _providers: []_ Before it was possible to and specify flag but this is no longer supported in Angular CLI 7+. ng generate service some-feature --moduleĀ ../some.module In case we want to scope our service to some component or module we have to remove the content of the decorator. Then we can import the service to the desired module and add it manually to the array. @Injectable() providers: [ ] Adjusting service dependency injection registration to scope it to the lazy loadedĀ module 7. Use ā to add libraries like Angular Material (orĀ others) ng addā Until now, we have been mostly talking about the execution of various schematics which were already available in our workspace. The schematics themselves usually created couple of new files and maybe added some import statement here and there to wire stuff upā¦ But what about libraries that need more extensive setupĀ work? Schematics cover our back yet again! The helps comes in the form of command and the corresponding (special) schematics implemented in the particular schematics package! ng add ng-add The most common example probably would be Angular Material, a great component library used in many Angular projects. Angular Material setup process is a bit more complicatedā¦. Obviously, we have to install the npm package @angular/material We have to decide if we want to go with pre-built theme or add our own custom theme We have to decide if we wan to support touch events and browser animations Such a nontrivial setup process is best handled using . ng add The selection capability is called āpromptsā and is a new feature of Angular CLIĀ 7+ Without we would have to install the package manually and then spend couple of minutes reading the docs to figure out how to set everything up! ng add It still might be worth it to add schematics to your open source library even if it doesnāt do much more than the package. That way people can add it using the usual workflow! Check out how to this minimal schematics in the library. PRO TIP: ng-add npm install example implement ng-add @angular-extensions/model š BONUS: UsefulĀ commands Run schematics without AngularĀ CLI Schematics are independent from the Angular CLI and can be executed outside of the workspace. All we have to do is to install which will give as command which we can run in our terminal of choice. npm i -g @angular-devkit/schematics-cli schematics Another possibility would be to us the package name and the command name are not the same so the execution would be quite cumbersomeā¦ and therefore I recommend to use global npm installation instead. npx. Unfortunately, in our case npx -p [@angular](http://twitter.com/angular "Twitter profile for @angular")-devkit/schematics schematics <command> List all available schematics schematics --list-schematics schematics-package-name: This command lists all available schematics from the specified package. The package has to be installed and available in the folder of the folder from where the command was executed. (Please note that the package name ends with character) node_modules/ : Example: in the workspace of the project generated by Angular CLI with installed package. schematics --list-schematics @ngrx/schematics: @ngrx/schematics š BONUS+: Amazing code completion capabilities! We might have noticed that the first line of the looks a bit funnyā¦ angular.json Example of code completion in the angular.json file powered by the JsonĀ Schema The $schema property is responsible for the super awesome code completion capabilities! Letās say we would like to add defaults to another schematics of our project. All we have to do is hit code completion key shortcut of our editor of choice and we would get the list of possible values! Very often together with a helpful description! Example of a property description provided by the code completion capabilities of theĀ IDE Thatās It ForĀ Today! I hope you enjoyed this article and will get more productive by using Angular Schematics in your projects! Please support this guide with your ššš using the š button on the left side and help to spread it to a wider audience š. Also, donāt hesitate to ping me if you have any questions using the article responses or Twitter DMs @tomastrajan Starting an Angular project? Check out ! Angular NgRx Material Starter Angular NgRx Material Starter with built in best practices, theming and muchĀ more! And never forget, future isĀ bright Obviously the bright future (šø by ) James Donaldson If you made it this far, feel free to check out some of my other articles about Angular and frontend software development in generalā¦ _There are many different ways how to handle RxJS subscriptions in Angular applications and weāre going to explore theirā¦_blog.angularindepth.com The Best Way To Unsubscribe RxJS Observable In The Angular Applications! _Most of the popular Angular state management libraries like NgRx expose application state in a form of a stream ofā¦_blog.angularindepth.com The Ultimate Answer To The Very Common Angular Question: subscribe() vs | async Pipe _Letās learn when and how to use new better Angular 6+ dependency injection mechanism with new providedIn syntax to makeā¦_medium.com Total Guide To Angular 6+ Dependency InjectionāāāprovidedIn vs providers:[ ] š _Animations make projects look much better_blog.angularindepth.com Total Guide To Dynamic Angular Animations That Can Be Customized At Runtime _Budgets is one of the less known features of the Angular CLI which helps you to keep application bundle sizes in checkā¦_medium.com How Did Angular CLI Budgets Save My Day And How They Can Save Yours
Share Your Thoughts