扩展 NX 生成组件

Extending NX generate component

在我的 Monorepo 中,我使用了两种类型的组件。

  1. 是应用程序的标准组件,nx g c foo在这里工作得很好。
  2. 是图书馆的图书馆组件。在这里,我专门使用辅助入口点。所以一个组件总是有一个 index.ts、一个 public_api.ts、一个 bar.module.ts 和一个 package.json 文件。

我的问题是,如何扩展 nx g c foo 的标准功能,以便它自动创建这些文件?

您可能想编写自己的原理图集。
请勾选 documentation, some nice articles and sources.
基本上,您从新组件原理图扩展的代码将如下所示:

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

export default function(schema: any): Rule {
    // add your custom code here

    return chain([
        externalSchematic('@nrwl/schematics', 'module', {
          ...module options
        }),
        externalSchematic('@nrwl/schematics', 'component', {
          ...component options
        }),

        // and here
    ]);
}

UPD

同样使用nx生成器编写API:

import { wrapAngularDevkitSchematic } from '@nrwl/devkit/ngcli-adapter';
import {
  Tree,
  formatFiles,
  generateFiles,
  joinPathFragments,
  names,
} from '@nrwl/devkit';
// this is your custom generator schema
import { Schema } from './models/schema.model';

export default async function (tree: Tree, schema: Schema) {
  const moduleGenerator = wrapAngularDevkitSchematic(
    '@schematics/angular',
    'module'
  );
  const componentGenerator = wrapAngularDevkitSchematic(
    '@schematics/angular',
    'component'
  );

  // it will create a custom module for you
  await moduleGenerator(tree, {
    name: ...module name,
    project: ...project to add module,
    path: ...path to add module file,
  });

  // it will create a custom component for you
  await componentGenerator(tree, {
    name: ...your name,
    project: ...project to add component,
  });

  // it's a branch where you can add your package.json and index.ts
  // you should create template files for them in ./files folder
  generateFiles(
    tree, // the virtual file system
    joinPathFragments(__dirname, './files'), // path to the file templates
    joinPathFragments('libs/'), // destination path of the files
    {
      ...schema,
      ...names(schema.name),
      tmpl: '',
    } // config object to replace variable in file templates
  );


  return tree;
}

查看他们的 tests 了解更多示例。