Currently, I am utilizing the ts-morph library and my objective is to add a new component to the declarations:
This is my initial setup:
@NgModule({
declarations: [],
imports: [],
providers: [],
})
Here is what I am aiming for:
@NgModule({
declarations: [ExampleComponent],
imports: [],
providers: [],
})
I have attempted the following without success:
const decorator = classDeclaration.getDecorator("NgModule");
const arg = decorator.getArguments()[0];
const declarationsProp = arg.getDescendants()
.find(d => d.getKind() === SyntaxKind.PropertyAssignment &&
(d.compilerNode as ts.PropertyAssignment).name === "declarations");
const array = declarationsProp.getFirstChildByKindOrThrow(SyntaxKind.ArrayLiteralExpression);
const closeBracketToken = array.getLastChildByKindOrThrow(SyntaxKind.CloseBracketToken);
sourceFile.insertText(closeBracketToken.getPos(), `, "something new!"`);
I also explored another solution but faced challenges with adding the new component:
const classDeclaration = sourceFile
.getClasses()
.find(
(classDeclaration) =>
classDeclaration.getName() === 'ExampleModule'
);
(classDeclaration.getDecorator('NgModule').getStructure()
.arguments as any[]).forEach((element) => {
addLog(LogType.Info, LogMode.Always, element);
});