使用Gulp按正确顺序连接js文件

3

我想使用gulp将一堆js文件按特定顺序拼接起来,其中要保证文件“custom.js”排在最后(尽管也可以是其他任何文件名)。

这是我的gulp任务:

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的名称之外,我可以做些什么来解决这个问题?
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. gulp.src
    • 选择src/scripts中的所有js文件
    • 排除src/scripts/custom.js
    • 加载src/scripts/custom.js
  2. 将流合并为main.js
  3. 压缩流
  4. 添加'.min'后缀
  5. 保存至static/js

关键部分在于先从全局匹配中排除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);
});

如果这种方法可行且您想要一个“更干净”的文件,您可以逐位将它们组合在一起。

谢谢!然而,看起来这根本没有添加custom.js...这里是我的gulpfile和目录结构的截图,如果有帮助的话。 - Flobin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接