扩展 Angular 原理图
Posted
技术标签:
【中文标题】扩展 Angular 原理图【英文标题】:Extending Angular Schematics 【发布时间】:2019-12-13 11:43:39 【问题描述】:扩展现有 Angular Schematic 的最佳方式是什么?我目前正在专门研究将一些默认代码添加到组件的规范文件中,但更一般的答案将不胜感激。
在我找到的教程中,它们显示了 externalSchematic 函数,这似乎是在正确的轨道上,但它们都没有显示如何更新/替换该原理图的模板文件。我已经尝试将模板复制到我的示意图中并应用/合并它们,但这似乎有点矫枉过正。 Angular 关于这个问题的文档似乎也很少。
有没有办法扩展默认原理图,还是我需要从头开始做所有事情?
【问题讨论】:
我想支持你的问题,因为我在这里遇到了同样的问题。现在,对我来说,hacky 的解决方案是从@schemics/angular 复制源代码并修改它们以满足我的需要。这是一个非常令人沮丧且不比从头开始更好的解决方法,但如果您真的需要,我可以将其发布在答案中。 我暂时继续前进;我确实订阅了this issue 以知道下次api文档何时出现,但我不知道那会是什么时候。 【参考方案1】:我绝对同意文档很少。我发现扩展现有原理图最有用的资源是这篇文章:https://blog.angular.io/schematics-an-introduction-dc1dfbc2a2b2
在“调用另一个原理图”标题下,它有一些关于如何修改新创建的组件的示例代码,这看起来就像您正在寻找的那样。在一天结束时,您应该调用现有的角度组件原理图,然后找到要修改的文件(在您的情况下是 .spec.ts 文件),最后插入您想要的新代码:
import Rule, SchematicContext, Tree, chain, externalSchematic from '@angular-devkit/schematics';
const sText = "test to insert";
return chain([
// Here you can modify options or do any preprocessing before calling the schematic (optional)
(cTree: Tree, _context: SchematicContext) =>
return cTree;
,
// Call the external schematic
externalSchematic('@schematics/angular', 'component', _options),
// Do whatever downstream processing you need to
(cTree: Tree, _context: SchematicContext) =>
// Find new component, which depends on where you put it in the tree
// Some approaches prefer to scan the entire tree looking for the new file,
// I prefer to narrow my search down a bit.
cTree.getDir('.')
.visit((sTempFilePath) =>
if (!sTempFilePath.endsWith(dasherize(_options['name']) + '.component.spec.ts'))
// Skip anything but the newly added typescript spec file
return;
// Now that we've found our new component file, read in the content
const cContentBuffer = cTree.read(sTempFilePath);
if (!cContentBuffer)
return;
// Add text at beginning of file (can customize to add anywhere)
cTree.overwrite(
sTempFilePath,
sText + cContentBuffer);
);
return cTree;
]);
最后一点 - 有时我发现我需要在自己的示意图中包含一个 schema.json 才能使用角度示意图。
希望有帮助!
【讨论】:
以上是关于扩展 Angular 原理图的主要内容,如果未能解决你的问题,请参考以下文章