Question

When compiling TypeScript, I get a lot of empty JavaScript files generated because their TypeScript counterparts contain only interfaces. There's currently no tsc option to suppress generation of these files. I'm using the gulp-tsc plugin to compile.

Is there a plugin or some other means to clean up empty files, or even a more general purpose gulp plugin that would allow me to delete files based on their name and content? Or is there a way to do this in gulp without using plugins?

Was it helpful?

Solution

I think you could relatively easily use node-glob to look for matching files outside gulp, something like this:

var glob = require('node-glob'),
    fs = require('fs);

gulp.task('delete-empty-files', function(cb) {
    glob('/path/to/generated/**/*.js', function(err, files) {
        files.forEach(function(file) {
            if(fs.statSync(file).size === 0) {
                fs.unlinkSync(file);
            }
        });
        // make sure the task runs asynchronously!
        cb();
    });
});

Alternatively, you could use gulp-tap to achieve a similar result, like so:

var tap = require('gulp-tap'),
    fs = require('fs);

gulp.task('delete-empty-files', function() {
    return gulp.src('/path/to/generated/**/*.js')
        .pipe(tap(function(file) {
            if(file.stat.size === 0) {
                fs.unlinkSync(file);
            }
        });
    });
});

They're pretty equal, really. I think the first one will be faster, because it won't have the extra stuff from gulp and vinyl-fs.

You might be able to add the {read: false} options to gulp.src() to speed things up, but that might also disable the .stat from being read. If you want to try it, you add it like this:

return gulp.src('/path/to/files/**/*.js', {read: false}).pipe(...)

OTHER TIPS

A better answer would be to just name those interface files with the .d.ts extension instead of .ts. No files are generated this way.

Alternatively, for anyone else facing similar issues, gulp-clip-empty-files solves this.

Remove empty files from stream. This prevent errors on some other plugins like gulp-sass and can be usefull removing placeholders.

The usage is quite simple...

var gulp = require('gulp');
var clip = require('gulp-clip-empty-files');

gulp.task('default', function () {
    return gulp.src('src/*.scss')
        .pipe(clip())
        .pipe(gulp.dest('dist'));
});

In this example all empty .scss files will be "clipped" (ignored?) before written out

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top