2

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.

galki
  • 8,149
  • 7
  • 50
  • 62

2 Answers2

5

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)

Chhirag Kataria
  • 278
  • 1
  • 9
  • 1
    Thanks, good advice. In case someone else needs an example how to use collection.json, you could also take a look at the xplat project: https://github.com/nstudio/xplat – Phil Mar 28 '20 at 07:39
  • This also provides a good resource if you're in the nrwl monorepo env - https://stackoverflow.com/questions/51610745/nrwl-nx-workspace-specific-schematics/52964600#52964600 – William Neely Sep 08 '20 at 21:30
  • Just want to add an upvote for not just a good answer, but a well-formulated answer. The link to the schematic introduction was really unnecessary but very helpful. – dudewad Aug 10 '22 at 00:15
3

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
electrichead
  • 1,124
  • 8
  • 20
  • You're right that there isn't much current documentation about this. We are working on a book on Nx as well as a blog article on schematics. I'll post those links when they are ready. – electrichead Dec 17 '18 at 19:34
  • So there’s no way to extend ‘ng g app’? – galki Dec 18 '18 at 09:34
  • ng g app uses a schematic from @angular/schematics. If you want to extend it, the only way is to create your own schematic (and extend the @angular/schematic in there) – electrichead Dec 21 '18 at 18:59