Я начал писать ответ о том, как это сделать с помощью API компилятора, но потом сдался, потому что он начинал становиться очень длинным.
Это легко возможно с ts-morph , выполнив следующее:
import { Project, PropertyAssignment, QuoteKind, Node } from "ts-morph";
// setup
const project = new Project({
useInMemoryFileSystem: true, // this example doesn't use the real file system
manipulationSettings: {
quoteKind: QuoteKind.Single,
},
});
const sourceFile = project.createSourceFile("/file.ts", `export const someConstant = {
name: 'Jhon',
lastName: 'Doe',
additionalData: {
age: 44,
height: 145,
someProp: 'OLD_Value'
/**
* Some comments that describes what's going on here
*/
}
};`);
// get the object literal
const additionalDataProp = sourceFile
.getVariableDeclarationOrThrow("someConstant")
.getInitializerIfKindOrThrow(ts.SyntaxKind.ObjectLiteralExpression)
.getPropertyOrThrow("additionalData") as PropertyAssignment;
const additionalDataObjLit = additionalDataProp
.getInitializerIfKindOrThrow(ts.SyntaxKind.ObjectLiteralExpression);
// remove all the "comment nodes" if you want to... you may want to do something more specific
additionalDataObjLit.getPropertiesWithComments()
.filter(Node.isCommentNode)
.forEach(c => c.remove());
// add the new properties
additionalDataObjLit.addPropertyAssignments([{
name: "eyeColor",
initializer: writer => writer.quote("brown"),
}, {
name: "email",
initializer: writer => writer.quote("someemail@gmail.com"),
}, {
name: "otherProp",
initializer: writer => writer.quote("with some value"),
}]);
// output the new text
console.log(sourceFile.getFullText());