扩展 NX 生成组件

问题描述

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

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

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

解决方法

您可能想编写自己的原理图集。
请检查 documentationsome nice articlessources
基本上,您从新组件原理图扩展的代码将如下所示:

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
    ]);
}

更新

使用 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 和此 article

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...