How to extract values of variables from a typescript file with gulp

I have a bunch of typescript files, and some of them export a constant called APIS.

I'm attempting to access these exports (with the goal of combining them into one file), but for some reason it's not working. I know I must be making a mistake somewhere, but I can't pinpoint what it is.

For instance, in my "services" folder, I have two files: service1.ts and service2.ts.

service1.ts:

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

service2.ts: does not have the APIS variable.

This is my gulpfile.js:

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

gulp.task('default', function() {
  return gulp.src('.../services/*.ts')
        .pipe(map(function(file) {
            return file.APIS;
          }))
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./test/'));
});

When I execute this task, it doesn't output anything. When I added console.log(file.APIS); to the map function, all values returned undefined (even though it is defined in service1.ts!).

Referencing: Extracting typescript exports to json file using gulp

EDIT: So, I attempted saving the exports in a .js file rather than a .ts file, and now I am able to access those variables using require:

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

  return gulp.src('./**/*.service.export.js')
        .pipe(map(function(file) {
            var fileObj = require(file.path);
            ...
          }))

Now if I try console.log(fileObj.APIS); I receive the correct values. However, I'm still unsure how to pass these values along and merge them into a single file. Is there a way to aggregate them into an array?

Answer №1

It's important to note that Gulp doesn't have built-in support for typescript files. The file being processed by Gulp is a vinyl-file, which has no direct knowledge of the TypeScript code it contains.

Update:

In light of your query, here's a potential solution you could explore:

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

gulp.task('test', function ()
{
    let allConstants = [];
    const stream = gulp.src('./**/*.output.service.js')
        .pipe(map(function(file)
        {
            const obj = require(file.path);
            if (obj.APIS != null)
                allConstants = allConstants.concat(obj.APIS);
            return file;
        }));

    stream.on("finish", function (cb)
    {
        // Implement custom formatting logic here
        const content = allConstants.map(function (constants)
        {
            return Object.keys(constants).reduce(function (aggregatedString, key)
            {
                return aggregatedString + key + " : " + constants[key];
            }, "");
        }).join(", ");

        fs.writeFile('formatted-output.txt', content, cb);
    });
    return stream;
});

Answer №2

Recommendation

For individuals looking to consolidate multiple variables into a single file, such as a common variables file, I recommend utilizing gulp-replace.

Instructions

To implement this method, create a new file, import it, and utilize designated tags within the file for organizing your variables.

Tips

If you are currently utilizing services, refrain from creating an array. Opt for an object structure (JSON) where each property represents a constant value. For example:

var constants =  {
   const_1: 0,
   const_2: 1,
   const_3: 2,
}

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

ExtJs encounters missing files in directory - Error: Module '<path>modern-app-3 ode_modules@senchaextpackage.json' not found

I am currently in the process of setting up a new ExtJs project by following the instructions provided here. Upon completing the installation of ext-gen, I proceeded to create a new app using the command ext-gen app -a -t moderndesktop -n ModernApp3, but ...

What is the best method for retrieving objects from a Meteor collection?

I'm a beginner with Meteor and I'm currently working on the introductory tutorial. However, I'm facing difficulties in retrieving data from a collection. Below is my JavaScript code: import angular from 'angular'; import angularM ...

What is the best method for validating a div element using Angular UI Bootstrap?

When I try to display an array of objects in a view, my issue arises when I place a div element inside the li and ul tags. The challenge now is to validate elements such as "number", "url", and "email" on blur and keyup events. Some elements may be require ...

Ensure that the type of the value passed to the callback function is enforced within the callback function in the

One of my jQuery plugins has a prompt function that accepts a callback function with setPrompt as the only parameter: Here is an example of how the code looks: obj.prompt(function(setPrompt) { setPrompt(10); }); I am wondering if it is possible to en ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

Converting JSON data from a PHP variable into a jQuery array: What you need to know

I attempted to retrieve addresses using the postcode and applied the getaddress.io site API with PHP. This resulted in a JSON dataset stored in the PHP variable $file. Now, I am tasked with converting this JSON result into a jQuery array. { "Latitude":-0. ...

The process of re-rendering a component is facilitated by applying various filters

Filters are an essential feature in my application, as they help limit the output of a list of users. You can see a live example of this concept in action on my codesandbox. The functionality allows users to apply multiple filters to narrow down their sea ...

Retrieving a video file from the input and showcasing it using Typescript

Currently, I have implemented this code in order to retrieve an image that has been "uploaded" into the browser using the <input type="file"> tag, and then sending the data to a component that will utilize it. fileReady(e) { let file: File = e[ ...

The CSS stylesheet is not being applied to the components in Next.js

I am currently facing an issue with styling my React/Next component. Despite trying to apply a stylesheet to enhance its appearance, the CSS doesn't seem to be taking effect. Could someone please provide guidance on how I can resolve this? I have att ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...

Retrieving JSON data via an AJAX call

Similar Question: Sending PHP json_encode array to jQuery I've created a function that searches a database for a specific name using $.post. It returns user details with matching search criteria in JSON format generated by PHP, like this: Arra ...

Assign an Angular model to an input in a dynamic manner

Currently, I am working on developing a compact spreadsheet feature for my angular application. My goal is to replicate a common functionality found in spreadsheets where users can click on a cell and then modify its value using a larger input field at the ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

Show a variety of months using a datepicker arranged neatly in rows and columns

I need to display 13 months using multidatespicker. I achieved this with the following code: $(document).ready(function(){ $('#my_calendar').multiDatesPicker({ numberOfMonths: [4, 4], dateFormat: 'dd-mm-yy&a ...

Comparison between a Typescript optional field and a field that has the potential to be undefined

Can you clarify the contrast between an optional field and a T | undefined field? export interface Example { property1: string | undefined property2?: string } ...

Issue encountered with Vue.js build configuration not being loaded while running on the build test server

I am working on a Vue 2 project and facing an issue with loading configuration settings from a config.json file. My router\index.ts file has the line: Vue.prototype.$config = require('/public/config.json') The config.json file contains imp ...

Initiate Action Upon Visibility

After discovering this script that creates a counting effect for numbers, I realized it starts animating as soon as the page loads. While I appreciate its functionality, I would prefer it to only initiate when the element is in view; otherwise, the animati ...

Select an option from the dropdown menu to populate the contents of the second dropdown list

The provided code dynamically populates the initial dropdown list with unique pants brands: $.each(pantsBrands, function(i){ var li = $('<li>') .appendTo(pantsList); var aaa = $('<a>') .text(pantsBra ...