【发布时间】:2019-09-05 23:54:36
【问题描述】:
我想为 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 是如何工作的。如果我从目录 /src/app/modules/foo 中执行ng g component bar,那么将在该目录中生成一个新组件。这是我需要复制的行为。
这是我的工厂。现在它显然是用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);
};
}
【问题讨论】:
-
这应该默认使用
ngcli。你能发布你的工厂吗? -
我在上面加了工厂。
标签: angular angular-cli angular-schematics