我想为 Angular 创建一个自定义原理图,它将在与执行原理图相同的目录中创建一个文件。我关注了这篇文章,但我不确定如何将新文件添加到所需的目录中。(https://developer.okta.com/blog/2019/02/13/angular-schematics#create-your-first-schematic)
例如,如果我有以下目录结构:
src/app/ !-- Angular Root
|- modules
|_ foo
|- foo.component.ts
|_ foo.component.html
|- app.component.ts
|- app.component.html
|_ app.module.ts
如果我确实执行以下命令:
> cd /src/app/modules/foo
> ng g my-component:my-component
我希望新创建/更新的文件位于 /src/app/modules/foo 目录而不是根目录中。想想 ng generate 是如何工作的。如果我ng g component bar
从目录 /src/app/modules/foo 中执行,那么将在该目录中生成一个新组件。这是我需要复制的行为。
这里是我的工厂。现在它显然是针对根目录的,project.root
但是我没有找到任何替代方法,如果我不提供路径,那么我会收到错误消息。如何获取当前路径(src/app/modules/foo)来存储options.path
?
export function setupOptions(host: Tree, options: any): Tree {
const workspace = getWorkspace(host);
if (!options.project) {
options.project = Object.keys(workspace.projects)[0];
}
const project = workspace.projects[options.project];
options.path = join(normalize(project.root), 'src');
return host;
}
// You don't have to export the function as default. You can also have more than one rule factory
// per file.
export function myComponent(_options: any): Rule {
return (tree: Tree, _context: SchematicContext) => {
setupOptions(tree, _options);
const movePath = normalize(_options.path + '/');
const templateSource = apply(url('./files/src'), [
template({ ..._options }),
move(movePath),
forEach((fileEntry: FileEntry) => {
if (tree.exists(fileEntry.path)) {
tree.overwrite(fileEntry.path, fileEntry.content);
}
return fileEntry;
})
]);
const rule = mergeWith(templateSource, MergeStrategy.Overwrite);
return rule(tree, _context);
};
}