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

Can someone explain the meaning of the paragraph in the "Index Routes" section of the React-Router documentation?

Lesson 8 of the React-Router tutorial delves into the concept of "Index Routes", outlining the importance of structuring routes in a specific way. Here are some key points from their discussion: The tutorial suggests that while setting up the initial rout ...

What is a more efficient way to search and substitute text in NodeJS?

I am currently working on a task that involves reading a file, passing its contents and multiple arrays to a function, using regex to see if there are any matches, replacing them, and finally updating the file. The code I have put together may not be the ...

Discovering the specific marker that was clicked from a group of Google map markers

I have a collection of marker objects named markers. I am currently utilizing a for loop to assign event listeners to each one. However, I am encountering difficulty in determining which specific marker was clicked. This is the current code snippet I have ...

How can I determine the existence of an S3 bucket and, if it doesn't exist, create it using TypeScript CDK?

I am currently facing an issue where I need to verify the existence of a bucket in the account and either create a new one if it doesn't exist or use the existing bucket My attempt at achieving this is as follows: import {Bucket} from 'aws-cdk-l ...

Utilizing JavascriptExecutor in Selenium Webdriver to start playing a video

Is it possible to trigger the play function in a page's JavaScript jQuery code using JavascriptExecutor? Below is an example of code extracted from a website: <script type="text/javascript"> jQuery(document).ready(function($) { $('#wp_mep ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Implementing a JavaScript function that uses the AJAX method to confirm and update

I am currently attempting to update a database using the JavaScript confirm() function in combination with AJAX. My goal is to have "accepted_order.php" run if the user clicks "OK," and "declined_order.php" run if the user clicks "Cancel," all without caus ...

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

Pagination Component for React Material-UI Table

I am interested in learning about Table Pagination in React UI Material. Currently, my goal is to retrieve and display data from an API in a Material UI Table. While I have successfully implemented some data from the API into the Material UI Table, I am ...

Leverage the power of Angular and Node.js to dynamically generate and configure a new subdomain on an

Currently, I am tackling a project that involves generating sub domains dynamically based on the prefixes entered by users on my website. While everything is functioning properly on my localhost using diet.js and express-subdomain, errors are being encount ...

Cease the use of jQuery animations

My JavaScript code snippet looks like this: $.get("/<page>.php", "userid='.$userid.'&"+status, function(data){ $("#status").show("fast").html(data).delay(4000).hide("fast"); }); On a page with multiple links triggering thi ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

How to download a dynamically generated PHP file to your local machine

I am trying to find a solution where the search results can be downloaded by the user and saved on their computer. Currently, the file is automatically stored on the server without giving the user an option to choose where to save it. In the search form, ...

Incorporating a setup file into my JavaScript project

In my JavaScript project, I have both frontend and backend codes (NodeJS). Here is the folder structure for my production environment: /prod /server sourceCode1.js sourceCode2.js ... sourceCodeN.js index.js ...

Obtaining a group object when the property value matches the itemSearch criteria

What is the best way to extract specific objects from a group when one of their properties has an array value, specifically using _.lodash/underscore? { "tileRecords" : [ { "tileName" : "Fama Brown", "tileGroup" : ["Polished", "Matt", ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

Retrieve JavaScript functions as JSON or text in AngularJS and execute them

Currently, I am working on developing an AngularJS application and have come across a particular challenge that needs to be addressed: After making a web service call, I receive JavaScript code that looks like this: { "script":"function foo(a, b) { c = ...

NextJS: Retrieve the information in its initial state

Is there a way to retrieve the original format of a value? For example: The values in my textarea are: Name: Your Name Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f980968c8b9c94989095b994989095d79a9694">[email ...