Using Generators

Overview

Generators provide a way to automate many tasks you regularly perform as part of your development workflow. Whether it is scaffolding out components, features, ensuring libraries are generated and structured in a certain way, or updating your configuration files, generators help you standardize these tasks in a consistent, and predictable manner.

Generators can be written using @nrwl/devkit or @angular-devkit. Generators written with the @angular-devkit are called schematics. To read more about the concepts of @angular-devkit schematics, and building an example schematic, see the Schematics Authoring Guide.

The Workspace Generators guide shows you how to create, run, and customize workspace generators within your Nx workspace.

Types of generators

There are three main types of generators:

  1. Plugin Generators are available when an Nx plugin has been installed in your workspace.
  2. Workspace Generators are generators that you can create for your own workspace. Workspace generators allow you to codify the processes that are unique to your own organization.
  3. Update Generators are invoked by Nx plugins when you update Nx to keep your config files in sync with the latest versions of third party tools.

Invoking plugin generators

Generators allow you to create or modify your codebase in a simple and repeatable way. Generators are invoked using the nx generate command.

nx generate [plugin]:[generator-name] [options]
nx generate @nrwl/react:component mycmp --project=myapp

It is important to have a clean git working directory before invoking a generator so that you can easily revert changes and re-invoke the generator with different inputs.

Simplest Generator

1{
2  "cli": "nx",
3  "id": "CustomGenerator",
4  "description": "Create a custom generator",
5  "type": "object",
6  "properties": {},
7  "additionalProperties": true
8}
1export default async function (tree, opts) {
2  console.log('options', opts);
3}

Defining a generator schema

A generator's schema describes the inputs--what you can pass into it. The schema is used to validate inputs, to parse args (e.g., covert strings into numbers), to set defaults, and to power the VSCode plugin. It is written with JSON Schema.

Examples

1{
2  "cli": "nx",
3  "id": "CustomGenerator",
4  "description": "Create a custom generator",
5  "type": "object",
6  "properties": {
7    "name": {
8      "type": "string",
9      "description": "Generator name",
10      "x-prompt": "What name would you like to use for the workspace generator?"
11    },
12    "skipFormat": {
13      "description": "Skip formatting files",
14      "type": "boolean",
15      "alias": "sf",
16      "default": false
17    }
18  },
19  "required": ["name"]
20}

The schema above defines two fields: name and skipFormat. The name field is a string, skipFormat is a boolean. The x-prompt property tells Nx to ask for the name value if one isn't given. The skipFormat field has the default value set to false. The schema language is rich and lets you use lists, enums, references, etc.. A few more examples:

1{
2  "cli": "nx",
3  "id": "CustomGenerator",
4  "description": "Create a custom generator",
5  "type": "object",
6  "properties": {
7    "stringOrBoolean": {
8      "oneOf": [
9        {
10          "type": "string",
11          "default": "mystring!"
12        },
13        {
14          "type": "boolean"
15        }
16      ]
17    },
18    "innerObject": {
19      "type": "object",
20      "properties": {
21        "key": {
22          "type": "boolean"
23        }
24      }
25    },
26    "array": {
27      "type": "array",
28      "items": {
29        "type": "number"
30      }
31    },
32    "complexXPrompt": {
33      "type": "string",
34      "default": "css",
35      "x-prompt": {
36        "message": "Which stylesheet format would you like to use?",
37        "type": "list",
38        "items": [
39          {
40            "value": "css",
41            "label": "CSS"
42          },
43          {
44            "value": "scss",
45            "label": "SASS(.scss)"
46          },
47          {
48            "value": "styl",
49            "label": "Stylus(.styl)"
50          },
51          {
52            "value": "none",
53            "label": "None"
54          }
55        ]
56      }
57    },
58    "positionalArg": {
59      "type": "string",
60      "$default": {
61        "$source": "argv",
62        "index": 0
63      }
64    },
65    "currentProject": {
66      "type": "string",
67      "$default": {
68        "$source": "projectName"
69      }
70    }
71  }
72}

Sometimes, you may not know the schema or may not care, in this case, you can set the following:

1{
2  "cli": "nx",
3  "id": "CustomGenerator",
4  "description": "Create a custom generator",
5  "type": "object",
6  "properties": {
7    "name": {
8      "type": "string"
9    }
10  },
11  "required": ["name"],
12  "additionalProperties": true
13}

Because "additionalProperties" is true, the generator above will accept any extra parameters you pass. They, of course, won't be validated or transformed, but sometimes that's good enough.

If you want to learn more about the schema language, check out the core plugins at https://github.com/nrwl/nx for more examples.

Implementing a generator

The implementation is a function that takes two arguments:

  • tree: an implementation of the file system
    • It allows you to read/write files, list children, etc.
    • It's recommended to use the tree instead of directly interacting with the file system.
    • This enables the --dry-run mode so you can try different sets of options before actually making changes to the files.
  • options
    • This is a combination of the options from workspace.json, command-line overrides, and schema defaults.
    • All the options are validated and transformed in accordance with the schema.
    • You normally don't have to validate anything in the implementation function because it won't be invoked unless the schema validation passes.

The implementation can return a callback which is invoked after changes have been made to the file system.

Examples

1import {
2  Tree,
3  generateFiles,
4  formatFiles,
5  installPackagesTask,
6} from '@nrwl/devkit';
7
8interface Schema {
9  name: string;
10  skipFormat: boolean;
11}
12
13export default async function (tree: Tree, options: Schema) {
14  generateFiles(
15    tree,
16    path.join(__dirname, 'files'),
17    path.join('tools/generators', options.name),
18    options
19  );
20
21  if (!options.skipFormat) {
22    await formatFiles(tree);
23  }
24
25  return () => {
26    installPackagesTask(tree);
27  };
28}

The generator is an async function. You could create new projects and generate new files, but you could also update existing files and refactor things. It's recommended to limit all the side-effects to interacting with the tree and printing to the console. Sometimes generators perform other side-effects such as installing npm packages. Perform them in the function returned from the generator. Nx won't run the returned function in the dry run mode.

Devkit helper functions

Nx provides helpers several functions for writing generators:

  • readProjectConfiguration -- Read the project configuration stored in workspace.json and nx.json.
  • addProjectConfiguration -- Add the project configuration stored in workspace.json and nx.json.
  • removeProjectConfiguration -- Remove the project configuration stored in workspace.json and nx.json.
  • updateProjectConfiguration -- Update the project configuration stored in workspace.json and nx.json.
  • readWorkspaceConfiguration -- Read general workspace configuration such as the default project or cli settings.
  • updateWorkspaceConfiguration -- Update general workspace configuration such as the default project or cli settings.
  • getProjects -- Returns the list of projects.
  • generateFiles -- Generate a folder of files based on provided templates.
  • formatFiles -- Format all the created or updated files using Prettier.
  • readJson -- Read a json file.
  • writeJson -- Write a json file.
  • updateJson -- Update a json file.
  • addDependenciesToPackageJson -- Add dependencies and dev dependencies to package.json
  • installPackagesTask -- Runs npm install/yarn install/pnpm install depending on what is used by the workspaces.
  • names -- Util function to generate different strings based off the provided name.
  • getWorkspaceLayout -- Tells where new libs and apps should be generated.
  • offestFromRoot -- Calculates an offset from the root of the workspace, which is useful for constructing relative URLs.
  • stripIndents -- Strips indents from a multiline string.
  • normalizePath -- Coverts an os specific path to a unix style path.
  • joinPathFragments -- Normalize fragments and joins them with a /.
  • toJS -- Coverts a TypeScript file to JavaScript. Useful for generators that support both.
  • visitNotIgnoredFiles -- Utility to act on all files in a tree that are not ignored by git.
  • applyChangesToString-- Applies a list of changes to a string's original value. This is useful when working with ASTs

Each of those have detailed API docs. Check the API Docs for more information.

It's also important to stress that those are just utility functions. You can use them but you don't have to. You can instead write your own functions that take the tree and do whatever you want to do with it.

Composing generators

Generators are just async functions so they can be easily composed together. For instance, to write a generator that generates two React libraries:

1import {
2  Tree,
3  generateFiles,
4  formatFiles,
5  installPackagesTask,
6} from '@nrwl/devkit';
7import { libraryGenerator } from '@nrwl/react';
8
9export default async function (tree: Tree, options: Schema) {
10  const libSideEffects1 = libraryGenerator(tree, { name: options.name1 });
11  const libSideEffects2 = libraryGenerator(tree, { name: options.name2 });
12  await performOperationsOnTheTree(tree);
13  return () => {
14    libSideEffects1();
15    libSideEffects2();
16  };
17}

Testing generators

The Nx Devkit provides the createTreeWithEmptyWorkspace utility to create a tree with an empty workspace that can be used in tests. Other than that, the tests simply invoke the generator and check the changes are made in the tree.

1import { readProjectConfiguration } from '@nrwl/devkit';
2import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
3import createLib from './lib';
4
5describe('lib', () => {
6  it('should create a lib', async () => {
7    const tree = createTreeWithEmptyWorkspace();
8    // update tree before invoking the generator
9    await createLib(tree, { name: 'lib' });
10
11    expect(readProjectConfiguration(tree, 'lib')).toBeDefined();
12  });
13});