Search code examples
javascriptgulpgulp-concat

Add string to the beginning of a gulp stream


I have setup a gulpfile.js that will compile my directory of js files to one (minified) source. But I need a small snippet of code to proced it (initializing the object literal that they are modifying), but I cannot seem to figure out how to achieve this. (See gulpfile below)

var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
gulp.task('build', function() {
    return gulp.src('src/*.js')
        .pipe(concat('ethereal.js'))
        .pipe(gulp.dest('build'))
        .pipe(rename('ethereal.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('build'));
});
gulp.task('lint', function() {
    return gulp.src('src/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});
gulp.task('watch', function() {
    gulp.watch('src/*.js', ["lint", "build"]);
})

Each file in src modifies an object literal that I need to add to the very beginning of the output script

For example, src/Game.js is as follows:

Ethereal.Game = function() {
    // init game code
}

Notice how it assumes that Ethereal is a real object that it is modifying, which it is.

TL;DR

  1. How would I add a snippet of code to the beginning of a gulp stream file
  2. If that's not possible how would I be able to achieve such an effect with another tool?

Solution

  • Just make a file with the snippet to be included first and do this:

    src/first.js

    var Ethereal = function() {
        // define Ethereal class constructor and stuff
    }
    

    src/Game.js

    Ethereal.Game = function() {
        // init game code
    }
    

    Then in the gulpfile:

    gulp.task('build', function() {
        return gulp.src(['src/first.js', 'src/*.js'])
            .pipe(concat('ethereal.js'))
            .pipe(gulp.dest('build'))
            .pipe(rename('ethereal.min.js'))
            .pipe(uglify())
            .pipe(gulp.dest('build'));
    });
    

    This will output build/ethereal.js as

    var Ethereal = function() {
        // define Ethereal class constructor and stuff
    } 
    Ethereal.Game = function() {
        // init game code
    }
    

    or just use http://browserify.org/ and require the Ethereal module in every module that implements it.