当使用图表生成角度上的组件时,它将尝试将新生成的组件导入到NgModule中,为了使组件工作并节省时间,这是必须的。
但是,在创建我自己的图表时,我无法找到一种正确的方法来这样做,并将我的库导入app.Component.ts的NgModule中。当使用ng-add示意图时,如何让原理图自动将自己的条目添加到NgModule中?
示意图需要做两件事:
在此之前:
@NgModule({
declarations: [],
imports: [],
exports: []
})
export class appModule { }之后:
import {library} from 'library';
@NgModule({
declarations: [],
imports: [library],
exports: []
})
export class appModule { }我知道这样做的一个函数存在于角度发展工具包中,因为组件的“官方”原理图和使用它。我该怎么做呢?
发布于 2020-01-07 14:46:50
对于第一种情况,下面的代码将帮助您:
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);
}
}对于第二个问题,我不记得了,但是您可以检查角cli示意图存储库,看看它是如何处理模块之类的事情的。
干杯!
发布于 2021-10-07 23:27:34
这里有一个函数,它使用`@addImportToModule‘函数中的@示意图/角/实用程序/ast’utils‘.
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;
}在返回规则的其他函数的末尾,在我对chain([])的调用中.,我像这样调用这个函数(我需要将HttpClientModule添加到导入中,如果用户在x-提示选项中安装了flex布局,我也需要将FlexLayoutModule添加到imports中。还有多个其他实用程序函数,如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中的imports:[]以及顶层的import语句中。还有一个实用程序函数'buildRelativePath‘,它来自于’@示意图/角/实用程序/查找-模块‘,如果您需要从您所使用的模块所在的任何位置构建相对路径,它可以提供帮助。
https://stackoverflow.com/questions/59304074
复制相似问题