Guide to custom Angular Schematics

When creating a new Angular project, how many times have you thought of copying files and folders for an initial setup of your Angular project? I’ve done it a million times (okay, not million, but you get the point, right?).

Rationale behind using Schematics

Be it a personal project or an enterprise project, I always wish I could use my own template project to get a great kick off. I wanted to have my core module, graphQL module, all the Apollo dependencies automatically installed, ESLint, prettier and husky hooks configured and etc etc.. every time I started my project. BUTT, I always had to copy paste the exact folders and files every time. And I recently stumbled upon the concept of Schematics and it has made the start of the new project 2x faster.

What the heck is Schematics, after all?

Creating a new Schematic

To create a new schematics project we’re going to use an NPM package called schematics. You’ll need to install it globally, just like the Angular CLI.

npm install -g @angular-devkit/schematics-cli
schematics blank --name=angular-schematics
  • sample-schematics-project/index.ts is the code run by our schematic.
"scripts": {
"build": "tsc -p tsconfig.json",
"watch": "tsc -p tsconfig.json --watch",

}

Getting User Input

We’ve talked about how to create a dummy schematic, which doesn’t really do anything, let’s see how can e get user inputs and how can we create a dummy project.

  1. Number
  2. Boolean
  3. enum
Asking for user input

Calling “ng new” Schematic

Now, let’s talk about how can we create an Angular project using a schematic. We’re aware of ng new command, we’ll see how can we make our schematic call an external schematic.

Calling ng new schematic

Calling a custom Schematic and creating custom rules

Now let’s suppose we want that whenever we use this schematic we add certain files. For that, firstly we need to put all the files and folders in our project and you can also add placeholders inside files, using <%= optionName %>.

Update package.json

Now if we want to add a few dependencies to our project upfront we can easily do that with our schematics.

Read package.json
Updating package.json

Run the Schematic

schematics ./new-project/src/collection.json:angular-schematic new-app

Publish our Schematic

Now, once we have created our schematic we can publish it using npm publish and everyone can start using it.

Web Developer, loves to write about UI technologies

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store