1

我已经设置了一个 gulpfile.js,它将我的 js 文件目录编译为一个(缩小的)源。但是我需要一小段代码来处理它(初始化他们正在修改的对象文字),但我似乎无法弄清楚如何实现这一点。(参见下面的 gulpfile)

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"]);
})

src 中的每个文件都会修改我需要添加到输出脚本开头的对象文字

例如 src/Game.js 如下:

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

注意它是如何假设 Ethereal 是它正在修改的真实对象,它就是。

TL;博士

  1. 如何将一段代码添加到 gulp 流文件的开头
  2. 如果这是不可能的,我怎么能用另一个工具来达到这样的效果?
4

1 回答 1

2

只需先创建一个包含片段的文件,然后执行以下操作:

src/first.js

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

src/Game.js

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

然后在 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'));
});

这会将build/ethereal.js输出为

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

或者只是使用http://browserify.org/Ethereal并在实现它的每个模块中都需要该模块。

于 2015-01-25T22:39:58.213 回答