问题描述
在我的 Monorepo 中,我使用了两种类型的组件。
- 是应用程序的标准组件,
nx g c foo
在这里工作正常。 - 是一个库的库组件。在这里,我专门使用辅助入口点。所以一个组件总是有一个 index.ts、一个 public_api.ts、一个 bar.module.ts 和一个 package.json 文件。
我的问题是,如何扩展 nx g c foo
的标准功能,使其自动创建这些文件?
解决方法
您可能想编写自己的原理图集。
请检查 documentation、some nice articles 和 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
]);
}
更新
使用 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;
}