Quick Guide to Angular Schematics: How I Built My First Schematic

Stefanie Fluin
8 min readFeb 26, 2020

As a lover of SCSS, structure and organization, I’m always finding myself adding the full SCSS folder structure to my front end dev projects. The lazy developer in me (aka efficient developer) wanted one command line I could enter in my terminal that would scaffold it all out for me and create all the necessary files in a matter of seconds. Enter Angular Schematics 🤲… this is a basic quick guide to help get you started on how to get an Angular Schematic up and running.

What are Angular Schematics

In very basic terms — Angular Schematics allow you to modify existing Angular projects, typically for adding or modifying files. Often they are also used to add libraries to your projects but can also be used for much more complex things.

In my scss-scaffold schematic I wanted it to modify an Angular project the following way:

  • Add the SCSS base folders and directory files
  • Create a new style sheet
  • Rename the default existing style sheet (in case there is existing code you want to keep)
  • Update the project’s settings to point to the new stylesheet

You can check out the schematic repo here:

The NPM package is here:

Now let’s walk through how I got this set up!

Prerequisites

Base Requirements

  1. NodeJS
  2. NPM (Node Package Manager)
  3. Angular CLI (npm install -g @angular/cli@latest)

Schematics Requirements

Install Angular’s official schematics package to use in your terminal:

@angular-devkit/schematics-cli

Schematics Setup

  1. Create Schematic: Create a blank schematics project with the schematics CLI — pass it the name you want to give it using the “name tag”:
schematics blank --name=project-name
Angular Schematics Files Created with CLI

You’ll get the default set of files above when you create a blank schematics project:

2. Install Dependencies & Build: Install dependencies and build the schematics project to get everything going:

npm install && npm run build

Now you have a base project you can get started with and start adding logic.

Structure

There are four primary files you’ll want to get to know:

  • index.ts — This is where your logic code goes
  • schema.json — Schematic variables ( variables that are referenced in your logic )
  • schema.d.ts — Schematic variable definitions
  • collection.ts — Defines your “project” and the associated schematics through a list and the corresponding metadata (you’ll need this if you want ng add enabled

Advanced: You can also add prompts via your schema.json file with “x-prompt”.

My folder structure looked as follows:

src
|-- ng add** (originally project name)
|-- files / styles*
|-- index.ts
|-- schema.ts*
|-- collection.ts
*I added these
** I renamed this to ng add

Template Files

Template files are super helpful in this case because we want to copy over that structure entirely onto an existing project. In the scss-scaffold schematic I created the base folder and file structure to use SCSS in an Angular project, including the directory files (ex. _base-dir.scss).

Angular Schematics Files Structure for scss-scaffold
File Structure

Advanced: You can do much more with template files — take in variables and populate files based on user-input and other variables.

The Logic

Now with your template files in place, it’s time to do things! For the scss-scaffold schematic I kept all of the logic in the index.ts file. Here’s the break-down of the features and corresponding code:

  • Setup: Identify the Angular project and make sure it’s an Angular CLI project.
index.ts
  • Add Files Content: Add the folders and files from the template files and add them to the existing project.
  • Handle Existing SCSS File: If you’ve set up an Angular CLI project with SCSS as your default styles, the Angular CLI automatically creates a styles.scss file for you. Furthermore, a user might already have code in there that we might want to retain. The currently strategy (for now) identifies if there is such a file and renames it to original-styles.scss.
  • Update Config: Creating a new main stylesheet that everythingn flows into means that we also need to update the styles reference in the Angular configurationangular.json file so that it’s pointing to the newly created styles/styles.scss file.
  • Merge: Finally, we need to merge the staged tree into the base tree to apply all of the changes to the actual project.

Now with your logic in place, you’re ready to test on a real project (although I recommend you do this step by step to make sure things are going as planned).

Testing Schematic Locally

There may be more efficient ways of testing your schematic, but I liked the idea of running it locally on a “real” project, so this is what I did:

  1. Create a Test Project: Create a simple test project using the Angular CLI with the following commands and go into the project folder:
ng new dummy-project
cd dummy-projet

2. Link Schematic to Test Project: You’ll want to ink your schematic to your test project so that you can run it from within — linking will also build the schematic for you so you don’t have to run that separately when you make an update (it runs npm run build as part of the sequence):

// This path will vary depending on where you have your schematic project located relative to your test projectnpm link ../scss-scaffold

3. Run Schematic on Test Project: With the schematic now linked, you can run the schematic on the project:

schematics scss-scaffold:ng-add

4. Tada! Watch your changes apply to your dummy project.

It’s good practice to test your schematic periodically by running “npm run build” from within the schematics project to see if it gets hung up anywhere.

I like working in steps so that you can test one thing (ex. Adding a file), then another (ex. Locating an existing file), then another (ex. Modifying said file), etc. to make debugging easier.

Now, with all your logic in place, a working schematic, it’s time to make it accessible to others (if you so desire) by adding ng add support and publishing it to NPM (npmjs.com).

ng add Support

The cool thing about Angular Schematics is that it allows you to package it up to be used as an ng add your-awesome-thing command with the Angular CLI. This makes consumption super easy for everyone! All people need to remember is your schematic name.

In order to set the ng add functionality up, you need to add the ng-add information to your collection.json file.

Note that the factory hash reference (in this case "./ng-add/index#ngAdd”) is the main function in your index.ts file. In this case I also happened to name it ng add.

There you go! With that in place, it enables the use of ng add.

Tip: Dependency “Save” Flag

I was lucky enough to get a PR from Alan Agius who made me aware about the “save flag”. If your project is not required as a dependency, then you’ll definitely want to add this flag to your package.json file:

...“ng-add”: { 
“save”: false
}
..

Adding this flag makes it so that when someone uses ng add your-project it does not add your project as a dependency to theirs. scss-scaffold is only adding files, so it’s not required as a dependency for future functionality.

Now, on to publishing!

Deploying to NPM

The last step is to publish your package on NPM so it can be publically available.

Log In

You’ll need to create a NPM account first if you haven’t already. You can do this on the website or directly in the command line. Once you’re logged in, it’s good practice to verify this and then all you have to do is publish!

// Create an account if you don't already have an account
npm adduser
npm login// Verify that you are properly logged in to your account
npm whoam
// Publish your package
npm publish path

The npm publish command will prompt several questions for you to answer.

Keywords

Keywords are like tags to your project and allow other users to find your package. Make sure you add some good descriptive keywords so that people can find your cool new schematic :)

Making Updates

Make sure you either update the version number in you package.jsonfile or run npm version patch to bump up your version number and publish automatically.

npm publish
package.json

That’s it 💁‍♀️! Now you have a published Angular Schematic accessible via NPM that users can easily take advantage of using ng add!

Repo

I’ve chosen to host my repo on GitHub, but that’s obviously up to you! You can check it out down below:

Summary

Hope this helps you get started on your first Angular Schematic project! I think more people should be using schematics. Schematics are extremely useful for libraries, creating templates and basic building blocks.

Happy coding!

After-Thoughts

I wasn’t familiar with some of the basic JSON functions JSON.parse and JSON.stringify, so the hardest part to implement for me was the modification of an existing file ( angular.json ).

Altough this project works quite well on a new sparkly Angular 9 CLI project, there are a few other considerations and future features I’d like to add:

  • Ask the user if they want to keep their existing styles.scss file
  • Account for other styles.scss file locations
  • Accont for other existing *.scss files
  • Proper error messages to the user
  • Management strategy for multiple projects

There’s always room for improvement and innovation 😀

Resources

Here are some awesome resources that helped me a ton to get started! I followed them in this order but feel free to bounce around.

--

--

Stefanie Fluin

👱‍♀️#Designer #Developer #UXE passionate about Design Systems and Angular (@thecodermomma on 📷 Insta)