javascripttypescriptgulpgulp-concatgulp-plugin

Accessing typescript file variable values using gulp


I have several typescript files, some of them export a const named APIS.

I'm trying to access those exports (I want to concatenated all of them to a single file), but it doesn't seem to work. I'm obviously doing something wrong, but I'm not sure what.

For example, I have a folder named services, with 2 files: service1.ts, service2.ts.

service1.ts:

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

service2.ts: does not contain the APIS var.

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 run this task, I get nothing. When I added console.log(file.APIS); to the map function, I get undefined for all the values (although it is defined in service1.ts!).

This is following to: Extracting typescript exports to json file using gulp

EDIT: OK, so I tried saving the exports in a .js file instead of a .ts file, and now I can access those vars 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 get the correct values. What I'm still confused about is how I can pass these value on, and create a single file out of all these vars. Is it possible to push them into an array?


Solution

  • This will not work as you think it would work. Gulp itself knows nothing about typescript files, that file is a vinyl-file and has no knowledge about the typescript code within its content.

    Edit

    Based on your example, you can do something like this:

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var map = require('gulp-map');
    var fs = require('fs');
    
    gulp.task('test', function ()
    {
        var allConstants = [];
        var stream = gulp.src('./**/*.service.export.js')
            .pipe(map(function(file)
            {
                var obj = require(file.path);
                if (obj.APIS != null)
                    allConstants = allConstants.concat(obj.APIS);
                return file;
            }));
    
        stream.on("end", function (cb)
        {
            // Do your own formatting here
            var content = allConstants.map(function (constants)
            {
                return Object.keys(constants).reduce(function (aggregatedString, key)
                {
                    return aggregatedString + key + " : " + constants[key];
                }, "");
            }).join(", ");
    
            fs.writeFile('filename.txt', content, cb);
        });
        return stream;
    });