Customizing generator options

Adding a TypeScript schema

To create a TypeScript schema to use in your generator function, define a TypeScript file next to your schema.json named schema.ts. Inside the schema.ts, define an interface to match the properties in your schema.json file, and whether they are required.

1export interface GeneratorOptions {
2  name: string;
3  type?: string;
4}

Import the TypeScript schema into your generator file and replace the any in your generator function with the interface.

1import { Tree, formatFiles, installPackagesTask } from '@nrwl/devkit';
2import { libraryGenerator } from '@nrwl/workspace';
3
4export default async function (tree: Tree, schema: GeneratorOptions) {
5  await libraryGenerator(tree, { name: `${schema.name}-${schema.type || ''}` });
6  await formatFiles(tree);
7  return () => {
8    installPackagesTask(tree);
9  };
10}

Adding static options

Static options for a generator don't prompt the user for input. To add a static option, define a key in the schema.json file with the option name, and define an object with its type, description, and optional default value.

1{
2  "$schema": "http://json-schema.org/schema",
3  "id": "my-generator",
4  "type": "object",
5  "properties": {
6    "name": {
7      "type": "string",
8      "description": "Library name",
9      "$default": {
10        "$source": "argv",
11        "index": 0
12      }
13    },
14    "type": {
15      "type": "string",
16      "description": "Provide the library type, such as 'data-access' or 'state'"
17    }
18  },
19  "required": ["name"]
20}

If you run the generator without providing a value for the type, it is not included in the generated name of the library.

Adding dynamic prompts

Dynamic options can prompt the user to select from a list of options. To define a prompt, add an x-prompt property to the option object, set the type to list, and define an items array for the choices.

1{
2  "$schema": "http://json-schema.org/schema",
3  "id": "my-generator",
4  "type": "object",
5  "properties": {
6    "name": {
7      "type": "string",
8      "description": "Library name",
9      "$default": {
10        "$source": "argv",
11        "index": 0
12      }
13    },
14    "type": {
15      "type": "string",
16      "description": "Provide the library type",
17      "x-prompt": {
18        "message": "Which type of library would you like to generate?",
19        "type": "list",
20        "items": [
21          {
22            "value": "data-access",
23            "label": "Data Access"
24          },
25          {
26            "value": "feature",
27            "label": "Feature"
28          },
29          {
30            "value": "state",
31            "label": "State Management"
32          }
33        ]
34      }
35    }
36  },
37  "required": ["name"]
38}

Running the generator without providing a value for the type will prompt the user to make a selection.