Angular Schematics - 添加库到 NgModule 导入

标签 angular typescript angular-schematics

当使用 Schematics 在 Angular 中生成组件时,它会尝试将新生成的组件导入到 NgModule 中,这是强制性的,以便组件可以工作并节省时间。

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

原理图需要做两件事:

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

之前:

@NgModule({
  declarations: [],
  imports: [],
  exports: []
})
export class appModule { }

之后:

import {library} from 'library';

@NgModule({
  declarations: [],
  imports: [library],
  exports: []
})
export class appModule { }

我知道 angular devkit 中存在执行此操作的功能,因为组件的“官方”原理图等使用它。我该怎么做?

最佳答案

对于第一种情况,类似下面的代码可以帮助您:

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);
    }
}

第二个暂时不记得了,你可以查一下angular-cli schematics存储库,以便查看它是如何为模块之类的东西完成的。

干杯!

关于Angular Schematics - 添加库到 NgModule 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59304074/

相关文章:

javascript - 当我从使用服务获取的数组中删除一个元素时,它在哪里被删除?

angular-schematics - 原理图 "my-comp"无法解析出厂

javascript - Angular2 : How to access DOM-Element (inside Component) from index. html 与 Javascript

reactjs - 输入名称上的 React hook 表单 useFieldArray typescript 错误

angular-cli - 如何在 `angular.json` 中配置内联样式和 html 模板?

angular - 扩展 Angular 示意图

angular - 将 Angular 2 模块加载为子路由

angular - 在捕获到故障后,如何允许我的 HTTP 请求继续通过我的应用程序传播?

javascript - @Host装饰器如何在注入(inject)器树中工作

javascript - 在 Angular 应用程序中以树结构显示数据