当使用 Schematics 在 Angular 中生成组件时,它会尝试将新生成的组件导入到 NgModule 中,这是强制性的,以便组件可以工作并节省时间。
但是,在创建我自己的原理图时,我无法找到正确的方法来执行相同的操作并将我的库导入到 app.component.ts 的 NgModule 中。使用 ng-add schematics 时,如何让 schematic 自动将其自己的条目添加到 NgModule 中?
原理图需要做两件事:
- 导入库
- 将其添加到 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/