这是一个使用来自 `@schematics/angular/utility/ast-utils' utils 的 'addImportToModule' 函数的函数。
function _addImport(
importPath: string,
importName: string,
_options: Partial<Schema>,
tree: Tree
): Tree {
const appModulePath = `/${_options.projectName}/src/app/app.module.ts`;
const appModuleFile = tree.read(normalize(appModulePath)).toString('utf-8');
if (!appModuleFile) {
throw new SchematicsException('app.module.ts not found');
}
const result = new AddToModuleContext();
result.source = ts.createSourceFile(
appModulePath,
appModuleFile,
ts.ScriptTarget.Latest,
true
);
result.relativePath = importPath;
result.classifiedName = importName;
const importsChanges = addImportToModule(
result.source,
appModulePath,
result.classifiedName,
result.relativePath
);
const importRecorder = tree.beginUpdate(appModulePath);
for (const change of importsChanges) {
if (change instanceof InsertChange) {
importRecorder.insertLeft(change.pos, change.toAdd);
}
}
tree.commitUpdate(importRecorder);
return tree;
}
在我的其他返回规则的函数之一的末尾,在我对链([])的调用中,我这样调用了这个函数(我需要将 HttpClientModule 添加到导入中,如果用户安装了在选项 x-prompts 期间进行 flex 布局,我还需要将 FlexLayoutModule 添加到导入中。还有多个其他实用功能,例如 addDependencyToModule、addExportToModule 等,可用于调整任何 module.ts 文件
电话:
tree = _addImport(
'@angular/common/http',
'HttpClientModule',
_options,
tree
);
if (_options.dependencies.includes('flexLayout')) {
tree = _addImport(
'@angular/flex-layout',
'FlexLayoutModule',
_options,
tree
);
}
return tree;
这成功地将两个模块添加到我的导入中:app.module 中的 [] 以及顶部的导入语句。还有一个来自“@schemics/angular/utility/find-module”的实用函数“buildRelativePath”,如果您需要从您正在使用的模块所在的任何位置构建相对路径,它可以提供帮助。