Log*_*ite 5 angular angular-schematics
扩展现有 Angular 原理图的最佳方法是什么?我目前正在专门考虑将一些默认代码添加到组件的规范文件中,但更通用的答案将不胜感激。
在我发现的教程中,它们显示了 externalSchematic 函数,这似乎是在正确的轨道上,但它们都没有显示如何更新/替换该原理图的模板文件。我尝试过将模板复制到原理图中并应用/合并它们,但这似乎有点矫枉过正。Angular 关于此事的文档似乎也很少。
有没有办法扩展默认原理图,或者我需要从头开始做所有事情?
我绝对同意文档很少。我发现扩展现有原理图最有用的资源是这篇文章: 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;
}
]);
Run Code Online (Sandbox Code Playgroud)
最后一点 - 有时我发现我需要在我自己的示意图中包含 schema.json 才能利用角度示意图。
希望有帮助!
| 归档时间: |
|
| 查看次数: |
1024 次 |
| 最近记录: |