Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API.

Current file - 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
         */
    }
};

In the end, my desired outcome is as follows:

export const someConstant = {
    name: 'Jhon',
    lastName: 'Doe',
    additionalData: {
        age: 999,
        height: 3333,
        someProp: 'NEW_Value'
        eyeColor: 'brown',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93e0fcfef6f6fef2faffd3f4fef2faffbdf0fcfe">[email protected]</a>',
        otherProp: 'with some value'
    }
};

Answer №1

I began crafting a response on how to achieve this using the compiler API, but ultimately abandoned it due to its length.

You can effortlessly accomplish this task with ts-morph by following these steps:

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("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a3925272f2f272b23260a2d272b232664292527">[email protected]</a>"),
}, {
    name: "otherProp",
    initializer: writer => writer.quote("with some value"),
}]);

// output the new text
console.log(sourceFile.getFullText());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

What is the best way to incorporate an ID from a scala template into an AJAX request?

In my application built on the Play Framework 2.3.8, users can input questions and answers. The view class receives a List[Question] which is iterated through using a for each loop to display them: @for(question <- questionList){ <!-- Questions --& ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

How to Handle CRUD Errors in NodeJS using Mongoose and Return a Custom Response to the Client

Setup NodeJS 10 MongoDB Client side app : Angular 9 About In my NodeJS application, I have a controller and service that work together to create an entity and return a promise. Here's how it looks: Controller async create(@Body() entityData: an ...

Having trouble getting getStaticProps to display JSX in Next.JS

I'm currently facing an issue with rendering basic data from a locally hosted Strapi API in my Next.js project. Although the data is successfully logged in the console, I am unable to map it into JSX. Below is the API get function: export async func ...

Rendering template and data from a promise in AngularJS: A comprehensive guide

Hey there, I'm diving into the world of Angular and I've been struggling for the past couple of days trying to figure out a solution for this issue. Not entirely sure if my approach is right either. My goal is to create a simple page with a dyna ...

Having trouble retrieving the HTML content after deploying my application on Heroku

I encountered an issue with my index.js file in Express Node.js once I deployed the app on Heroku. In production, I'm getting an error that seems to indicate that the server is unable to find my index.html file. *-src ---index.html ---index.js * ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...

CSS compatibility across different browsers

Check out my jsFiddle for an example of an onHover event that changes the image. It's working perfectly in chrome, but not quite right in firefox. Any suggestions on how to fix it? Here's the jQuery function I'm using: $(document).ready(fu ...

Efficient method invocation for objects within an array using functional programming techniques

Is there a way to execute a method that doesn't require arguments and doesn't return anything on each object within an array of objects that are all the same type? I've been trying to find a solution without resorting to using a traditional ...

Detecting collisions on a pixel-by-pixel basis within Javascript/Jquery/Gamequery

Currently, I am working on developing a web game using Jquery with the GameQuery plugin. However, I have encountered an issue where the GameQuery plugin does not support per pixel collision detection, only bounding boxes collision detection. Is there a way ...

Using TypeScript, you can utilize RxJS to generate a fresh Observable named "Array" from a static array

I've successfully created an observable from an array, but the issue is that its type shows as Observable<number> instead of Observable<number[]> getUsers(ids: string[]): Observable<number[]> { const arraySource = Observable.from ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

Issue with Promise failing to trigger .then() following fetch to Express API/Mongoose request

Can someone shed light on why I am unable to return a promise and invoke .then() on it? I am creating an inventory system for my collection of Pokemon cards using a react front-end and an express backend. When I click the "increase inventory" button on th ...

Determining block time based on block number within Polygon Mumbai Testnet

Is there a dependable method to identify the production time of a specific block in Polygon Mumbai Testnet using only its block number? I am unable to utilize an Api for this purpose and am seeking a more user-friendly computational solution. Any suggest ...

What is the best way to rearrange an array in React?

I need help with manipulating an array of strings displayed in a list. Each string should have the ability to move up or down within the array. For example: const array = ["hello", "world", "cool"] moveUp("world", 1) // (moveUp: value:string, index: nu ...

What is the best way to verify if the ReactDOM.render method has been invoked with a React component as an argument

Here's the code snippet: index.tsx: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export function Loading(props) { return <div {...props}>loading...</div>; } export class MyComponent e ...

Capturing and setting form element values within a Javascript Module Pattern

I'm looking to streamline my form element access using the Module pattern. The goal is to eliminate redundancy by organizing everything under a single module. How can I achieve this without having to directly call the Anonymous function within the mo ...

Is it possible to refrain from using the object variable name in an ng-repeat loop?

When utilizing an ng-repeat directive to loop through an array, the syntax requires ng-repeat="friend in friends". Inside the template, you can then use the interpolation operator like this {{friend.name}}. Is there a way to directly assign properties to ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...