javascript - Typescript derleyici API'si ile nesneyi okuma ve güncelleme
TypeScript derleyici API'si benim için yenidir ve görünüşe göre bir şeyleri kaçırıyorum. Derleyici API'si ile ts dosyasındaki belirli bir nesneyi güncellemenin yolunu arıyorum
Mevcut dosya - some-constant.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
*/
}
};
Sonuçta, böyle bir şey almak istiyorum:
export const someConstant = {
name: 'Jhon',
lastName: 'Doe',
additionalData: {
age: 999,
height: 3333,
someProp: 'NEW_Value'
eyeColor: 'brown',
email: '[email ',
otherProp: 'with some value'
}
};
Cevap #1
Bunu derleyici API ile nasıl yapacağımı anlatan bir cevap yazmaya başladım, ama sonra vazgeçtim çünkü gitgide çok uzun olmaya başlamıştı.
Bunu ts-morph ile kolayca şu şekilde yapmak mümkündür:
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("[email "),
}, {
name: "otherProp",
initializer: writer => writer.quote("with some value"),
}]);
// output the new text
console.log(sourceFile.getFullText());
