3

我正在尝试用 gulp 连接一堆 js 文件,但是按照特定的顺序。我希望最后一个名为“custom.js”的文件(可以是任何其他文件名,不过。

这是我的吞咽任务:

gulp.task('scripts', function() {
  return gulp.src(['src/scripts/**/!(custom)*.js','src/scripts/custom.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    //.pipe(gulp.src('src/scripts/**/*.js')) not needed(?)
    .pipe(order([
        '!(custom)*.js', // all files that end in .js EXCEPT custom*.js
        'custom.js'
    ]))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('static/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('static/js'))
    .pipe(notify({ message: 'Scripts task complete' }));
});

但是,这只是按字母顺序连接文件。除了将 custom.js 文件重命名为 zzz-custom.js 之类的文件外,我能做些什么来解决这个问题?

4

1 回答 1

4

你需要一些类似的东西......

gulp.task('scripts', function() {
    return gulp.src(['src/scripts/**/*.js','!src/scripts/custom.js', 'src/scripts/custom.js'])
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('static/js'));
});
  1. 吞咽.src
    • globs src/scripts 中的所有 js 文件
    • 不包括 src/scripts/custom.js
    • 加载 src/scripts/custom.js
  2. 将流连接到 main.js
  3. 丑化流
  4. 添加“.min”后缀
  5. 保存到静态/js

关键部分是首先从 glob 中排除 custom.js,然后添加它。

** 编辑 **

好吧,我想你可以分解这些步骤。不是最优雅但应该做的工作:

var sequence = require(‘run-sequnce’);
var rimraf = require(‘rimraf’);

// This gets called and runs each subtask in turn
gulp.task('scripts', function(done) {
    sequence('scripts:temp', 'scripts:main', 'scripts:ugly', 'scripts:clean', done);
});

// Concat all other js files but without custom.js into temp file - 'main_temp.js'
gulp.task('scripts:temp', function() {
    return gulp.src(['src/scripts/**/*.js','!src/scripts/custom.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(concat('main_temp.js'))
    .pipe(gulp.dest('static/js/temp'));
});

// Concat temp file with custom.js - 'main.js'
gulp.task('scripts:main', function() {
    return gulp.src(['static/js/temp/main_temp.js','src/scripts/custom.js'])
    .pipe(concat('main.js'))
    .pipe(gulp.dest('static/js'));
});

// Uglify and rename - 'main.min.js'
gulp.task('scripts:ugly', function() {
    return gulp.src('static/js/main.js')
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('static/js'));
});

// Delete temp file and folder
gulp.task('scripts:clean', function(done) {
    rimraf('static/js/temp', done);
});

如果它以这种方式工作并且您想要一个“更干净”的文件,您也许可以将它们一点一点地组合起来

于 2016-01-03T08:07:03.033 回答