Angular Schematics - 将库添加到 NgModule 导入中

and*_*oga 2 typescript angular angular-schematics

当使用 Schematics 在 Angular 中生成组件时,它会尝试将新生成的组件导入到 NgModule 中,这是为了组件正常工作并节省时间所必需的。

但是,在创建自己的原理图时,我无法找到正确的方法来执行相同的操作并将我的库导入到 app.component.ts 的 NgModule 中。使用 ng-add 原理图时,如何让原理图自动将自己的条目添加到 NgModule 中?

原理图需要做两件事:

  1. 导入库
  2. 将其添加到 NgModule 导入中

前:

@NgModule({
  declarations: [],
  imports: [],
  exports: []
})
export class appModule { }
Run Code Online (Sandbox Code Playgroud)

后:

import {library} from 'library';

@NgModule({
  declarations: [],
  imports: [library],
  exports: []
})
export class appModule { }
Run Code Online (Sandbox Code Playgroud)

我知道 Angular devkit 中存在执行此操作的函数,因为组件等的“官方”原理图使用了它。我会怎样做同样的事情?

Kin*_*oja 5

对于第一种情况,类似下面的代码将对您有所帮助:

export function addImportStatement(tree: Tree, filePath: string, type: string, file: string): void {
    let source = getTsSourceFile(tree, filePath);
    const importChange = insertImport(source, filePath, type, file) as InsertChange;
    if (!(importChange instanceof NoopChange)) {
        const recorder = tree.beginUpdate(filePath);
        recorder.insertLeft(importChange.pos, importChange.toAdd);
        tree.commitUpdate(recorder);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于第二个,我现在不记得了,但您可以检查angular-cli 原理图存储库,以了解它是如何对模块等内容完成的。

干杯!