How to extend an existing angular schematic

2.8k views Asked by At

I'd like to customize the ng g app schematic so that calling ng g app myapp will create myapp/src/environments/environment.ts file like so:

import { environment as baseEnvironment } from '@myworkspace/environments/environment';

export const environment = Object.assign(
  { production: false },
  baseEnvironment
);

The Nx docs show how to set things up but do not show any code examples, which would be greatly appreciated.

2

There are 2 answers

3
electrichead On

You can create a custom schematic to do this in your Nx workspace.

ng g workspace-schematic my-new-app

This will create a new schematic under tools/schematics. You can edit the index.ts file that's created to insert your own code.

    import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';

export default function(schema: any): Rule {
    return chain([
        externalSchematic('@nrwl/schematics', 'app', {
          name: schema.name
        }),

        // add your custom code here
    ]);
}

You can then run this with this command:

 npm run workspace-schematic my-new-app -- somename
3
Chhirag Kataria On

Yes, there is a way to do this, and quite easily :) create a schematic, and add “extends”: [ “@schematics/angular” ] to the collection.json of this schematic. (or @nrwl/schematics if you’re using that)

define your schematic as ‘app’ (since that’s the function you want to edit) — and the factory would use externalSchematic method to call angular’s/nrwl’s create app schematic, and you can add your environment file to this created tree.

Done! (I have assumed the knowledge of creating a schematic is known, if not, https://blog.angular.io/schematics-an-introduction-dc1dfbc2a2b2 should be a good starting point)