Florent Fortat

Stuff

How Angular 6 Schematics works

Publié par MaxguN dans Webdev - 30.05.2018 - 21:41

Package Manager - Trala

I've been working on a kind of a package manager for my day job lately. It's aimed at handling our own concept of packages inside a modular Angular project. It's called trala, it's published on NPM and the sources are on Github. As of writing this, the tool is very rough and very specific to our needs but I aim to make it a generic tool.

For now, trala can do the following operations:

  • init -- initialize a project by cloning a skeleton git repository (hardcoded for now), create a branch specific to this new project and retrieve default modules that should be coming with the project (the theme we use, also hardcoded)
  • install -- add a package to the project by cloning it's repository, creating a branch from a given or the latest version tag and import all the modules and services it exports into the app module
  • remove -- remove the package from the file system and remove the imports added with the install command
  • update -- update a package to a newer version (basically doing a remove then install)

The part that has taken me most time into creating this tool has been the import of modules and services into the application.

Because Schematics.

Schematics

Angular has a devkit package that includes a tool called Schematics. This tool is used to make operations on the filesystem like generating files, deleting files, editing files following implemented rules. The thing is, schematics is very badly documented. I've spent a good amount of hours to procrastinate understand how schematics works and now I'm going to document it a bit here.

Create a collection

A collection is a bunch of schematics grouped together. You can find angular cli's collection here for exemple of the default collection for the schematics package here. The interesting part here is you can create your own collection in any npm package. To setup a collection, you need to do 2 things:

  • Create a folder where you will put a collection.json manifest and all your schematics in subfolders
  • Add a schematics entry in your package.json that points to your collection.json like this : 
    "schematics": "./dist/schematics/collection.json"

The collection.json format looks like this:

{
  "schematics": {
    "addModule": {
      "aliases": [ "am" ],
      "factory": "./add-module",
      "description": "Add a Tralalere module.",
      "schema": "./add-module/schema.json"
    },
    "removeModule": {
      "aliases": [ "rm" ],
      "factory": "./remove-module",
      "description": "Remove a Tralalere module.",
      "schema": "./remove-module/schema.json"
    }
  }
}

Add Schematics