Utilizing Gulp to Convert TypeScript Exports into a JSON File

I have a set of TypeScript files, some of which export a specific variable - named APIS - which contains an array of objects. My goal is to extract the values from all of these exports and save them into a JSON file using Gulp.

Let's consider a directory called services, containing 3 files: service1.ts, service2.ts, and service3.ts.

service1.ts:

...
export const APIS = [ { "field1" : "blabla" } ];

service2.ts:

...
export const APIS = [ { "field2" : "yadayada" }, { "field3" : "yadabla" } ];

service3.ts: - does not export the APIS variable.

My objective is to utilize Gulp to create a JSON file structured like this:

[ { "field1" : "blabla" }, { "field2" : "yadayada" }, { "field3" : "yadabla" } ]

gulpfile.js - the ??? represents the missing code.

gulp.task('default', function () {
    return gulp.src('.../services/*.ts')
            .pipe(???)
            .pipe(concat('export.json'))
            .pipe(gulp.dest('./test'));
});

Since I am new to TypeScript and Gulp, I am unsure of how to accomplish this task... any suggestions? :)

EDIT: After realizing there is no ready-made solution for this, it seems I will have to create my own task or plugin. However, I am uncertain about how to proceed with that. Ideally, I am looking for a Gulp plugin (or a combination of plugins) that can handle TypeScript/JavaScript files as objects with properties. This way, I can extract the necessary variable from the file.

My search did not yield such a plugin, only ones that manipulate strings - Treating my TypeScript file as a string and using regex search seems overly complex to me. Am I overlooking something? Is there a more direct method to achieve this?

Answer №1

When working with Typescript, it is essential to leverage the compiler API to properly analyze and comprehend the ts-code. Unfortunately, the availability of a gulp plugin implementing this API seems to be lacking.

Considering this limitation, it may be beneficial to explore alternative approaches to address your issue or consider utilizing regex to extract the necessary constants. Alternatively, you could develop your own custom gulp plugin utilizing the compiler API.

Answer №2

After experimenting, I discovered a solution that worked for me. Sharing it here in case it benefits others. :)

Instead of saving the exports as .ts files, I opted for .js files, like so:

service2.export.js:

exports.APIS = [ { "field2" : "yadayada" }, { "field3" : "yadabla" } ];

Following the guidance from this answer: I crafted a gulp task like this:

var gulp = require('gulp');
var concat = require('gulp-concat');
var map = require('gulp-map');
var fs = require('fs');

var allServices;

gulp.task('default', function() {

    var allServices = [];

    var stream = gulp.src('./**/*.export.js')
        .pipe(map(function(file) {
            var obj = require(file.path);
            if (obj.APIS != null) {
                allServices.push.apply(allServices, obj.APIS);
            }
            return file;
        }));

    stream.on("end", function (cb)
    {   
        fs.writeFile('./export.json', JSON.stringify(allServices), cb);
    });

    return stream;
});

As a result, the contents of export.json now look like this:

[ { "field1" : "blabla" }, { "field2" : "yadayada" }, { "field3" : "yadabla" } ]

It perfectly aligns with my expectations.

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

I am confused as to why my function is selecting all the checkboxes when it should only be selecting one

I am facing an issue while creating a list with checkboxes in reactJS. Whenever I click on a single checkbox, all the checkboxes get selected instead of just the one that was clicked. How can I resolve this problem? const checkHandler = () => { if ( ...

Interactive elements embedded within an image - digital board game

I'm currently working on integrating a board game into React, and I am facing some difficulties in figuring out how to translate the board squares shown in the image into data. Is there a method through which I can assign unique IDs to each square di ...

A destructured object with a Typescript interface

While working on a React / TypeScript project, I encountered an error involving destructuring an object. The issue arises when I try to destructure notificationData within the publish function. An error message stating "Property 'messages' does ...

The issue with Rails and Ajax request failing to load arises when including a .js.erb file

I have a project in mind for a simple website, akin to a stock tracker. One of the key features I'm trying to implement is using ajax to get results without having to reload the entire page. Although I am able to retrieve the HTML with the desired dat ...

Tips for customizing the background color of the MUI Menu Popover within a TextField that has the select property

In my quest to customize the appearance of a popover or menu in a TextField with the 'select' property, I referred to MUI customization docs for guidance. Successfully changing the text and label color of a TextField using the code below: const u ...

Tips on populating the gap between dual cylinder meshes in Three.js

I'm working on a code that creates cylinders using a series of 3D vectors, but I'm encountering an issue with unsightly gaps between them: https://i.sstatic.net/E17Gm.png Does anyone have any tips on how to fill in these gaps in the latest vers ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info-> ...

What is the reason for ng-maxlength not being re-evaluated dynamically?

Within my form, there is a single input field and three checkboxes. Depending on the checkbox selected, the maximum length of the input field should adjust accordingly. The initial setup for the input field looks like this: <input placeholder="ID" typ ...

Guide on how to display normal vectors on the surface of an object using three.js

After discovering an intriguing example on threejs.org that showcases drawing arrow normals, I realized that it is exactly what I need. However, the arrows are complex objects created by ArrowHelper. Upon examining the source code, I came across the setDir ...

The ion-datetime in Ionic 4 ensures that the floating label always remains visible, even when the input

When an ion-datetime field in Ionic 4 has no value, the label always floats as shown below. Here is my code snippet: <form [formGroup]="statusHandlerForm"> <ion-item class="input-container " align-items-center no-padding> <ion-la ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

Discovering modifications in a scope variable object with AngularJs

I found an interesting directive called angular-webspeech-directive Check out the HTML code below: <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>TestBed</title> <link da ...

What is the most efficient way to create multiple nested property objects in a shorter amount of time?

Currently, I am utilizing mongoDB for a data migration project where queries are written in plain JavaScript/JSON format: queryObj = {}; // main object passed to mongodb for queries The code snippet below is causing an error: queryObj[inObj.row]['$ ...

Tips for identifying the amount of <ul> elements contained within every div

Dealing with a large file structured in the same way, I am looking for a method to isolate a specific div, determine the number of ul's within it, and then iterate through each one to extract the value of every li element. <div class="experiment ...

Combining Nested Objects in MongoDB

I have searched extensively for a solution but I am struggling to find a resolution to my issue. I have two MongoDB (Node.JS) collections: user & statistics. My goal is to merge the results using aggregate. Below are the structures of the collection ...

Concluding the dialogue once the post request has been successfully processed

My tech stack includes React, Redux, NodeJS, and ExpressJS. For the front-end, I'm utilizing material-ui. Within my application, I have implemented a dialog that allows users to input information and sign up. Upon clicking submit, a POST request is in ...

gulp-favicons malfunctioning in gulp automation process

After integrating gulp-favicons into my gulp workflow, I encountered a problem when trying to use favicons = require('gulp-favicon');. Surprisingly, the issue arises even before running the task, displaying the following error: /Volumes/SK Repo ...

Localization of text in jQuery timeago.js

I have implemented J Query time ago to display date and time on my website. I am currently working on a multilanguage website where I want the time ago message to show as "1 min ago" for English users and "1 دقیقه قبل" for Farsi users. Can I achi ...

Is there a way to smoothly slide an element in the same way another element can be dragged out

I am currently using AngularJS. My goal is to achieve the following: When the 'Fade in' button is clicked, a hidden element should slide out from the left side. It should appear behind the 'MAIN BASE' element, giving the illusion that ...

Obtain an array dynamically through a manufacturing plant

I'm currently working on extracting information from a factory and displaying it in a dynamic manner. Previously, I used the following approach: <div class="articlePage"> <h4> {{ posts[0].title }} </h4> <span style="color: # ...