简体   繁体   English

扩展NX生成组件

[英]Extending NX generate component

In my Monorepo, there are two types of components that i am using.在我的 Monorepo 中,我使用了两种类型的组件。

  1. Is a standard component for applications, and nx gc foo works fine here.是应用程序的标准组件, nx gc foo在这里工作正常。
  2. Is a library component for a library.是库的库组件。 Here, I exclusively use secondary entry points.在这里,我专门使用辅助入口点。 So a component always has an index.ts, a public_api.ts, a bar.module.ts and a package.json file.所以一个组件总是有一个 index.ts、一个 public_api.ts、一个 bar.module.ts 和一个 package.json 文件。

My question is, how could I extend the standard functionality of the nx gc foo , so that it automatically creates these files?我的问题是,如何扩展nx gc foo的标准功能,以便它自动创建这些文件?

You probably want to write your own schematics collection.您可能想要编写自己的原理图集合。
Please check documentation , somenice articles and sources .请检查文档一些不错的文章来源
Basically your extending code from new component schematic will look like this:基本上,您从新组件原理图中扩展代码将如下所示:

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 UPD

The same written using nx generators API:使用 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;
}

See their tests for more examples.有关更多示例,请参阅他们的测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM