Gulp Concat文件按顺序排列,然后是任何其他js文件

时间:2016-04-04 16:15:55

标签: javascript node.js gulp

如何按特定顺序添加一些js文件,然后再添加其他任何js文件?我在想这样做:

var concat = require('gulp-concat');

gulp.task('scripts', function() {
  return gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js', './lib/**/*.js'])
    .pipe(concat('all.js'))
    .pipe(gulp.dest('./dist/'));
});

由于我正在使用glob,因此不确定是否会重新添加已经合并的文件。

2 个答案:

答案 0 :(得分:2)

Gulp-order might be what you're looking for. I haven't tested the following code, but the docs somewhat suggest that it will work. If it doesn't work, I'd suggest that you try to be more specific with the last globstar so that you're scoping to directories, if possible.

var order = require("gulp-order");

gulp.task('scripts', function() {
  return gulp.src('./lib/**/*.js')
    .pipe(order([
      'file3.js', 
      'file1.js', 
      'file2.js', 
      '**/*.js'
     ]))
    .pipe(concat('all.js'))
    .pipe(gulp.dest('./dist/'));
});

There's also an article with a working example.

答案 1 :(得分:0)

gulp.src() uses node-glob. If you look at the source code of node-glob the authors give a pseudo-code description of the algorithm (shortened, see source code for full pseudo-code):

// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them

What this means for you is:

Order is preserved. The files ./lib/file3.js, ./lib/file1.js and ./lib/file2.js will be emitted in that order if you explicitly pass them to gulp.src() in that order. No need to use gulp-order in that case.

No duplicates. Since the files are uniqed, none of them will be emitted twice in your gulp stream. In fact node-glob takes specific precautions to prevent duplicates for brace expansion:

nounique In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior.

As well as for symbolic links:

Note that symlinked directories are not crawled as part of a **, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like.

TLDR: Yeah, your code works.