Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend an existing angular schematic

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.

like image 476
galki Avatar asked Feb 06 '26 23:02

galki


2 Answers

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)

like image 90
Chhirag Kataria Avatar answered Feb 09 '26 14:02

Chhirag Kataria


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
like image 38
electrichead Avatar answered Feb 09 '26 14:02

electrichead



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!