4

扩展现有 Angular Schematic 的最佳方法是什么?我目前正在专门研究将一些默认代码添加到组件的规范文件中,但更通用的答案将不胜感激。

在我找到的教程中,它们显示了 externalSchematic 函数,这似乎是在正确的轨道上,但它们都没有显示如何更新/替换该原理图的模板文件。我已经尝试将模板复制到我的原理图中并应用/合并它们,但这似乎有点矫枉过正。Angular 关于这个问题的文档似乎也很少。

有没有办法扩展默认原理图,还是我需要从头开始做所有事情?

4

1 回答 1

3

我绝对同意文档很少。我发现扩展现有原理图最有用的资源是这篇文章: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 才能使用角度示意图。

希望有帮助!

于 2020-01-10T15:46:35.423 回答