Concat scripts in order with Gulp

后端 未结 17 1475
后悔当初
后悔当初 2020-11-28 01:51

Say, for example, you are building a project on Backbone or whatever and you need to load scripts in a certain order, e.g. underscore.js needs to be loaded befo

17条回答
  •  情深已故
    2020-11-28 02:42

    I have my scripts organized in different folders for each package I pull in from bower, plus my own script for my app. Since you are going to list the order of these scripts somewhere, why not just list them in your gulp file? For new developers on your project, it's nice that all your script end-points are listed here. You can do this with gulp-add-src:

    gulpfile.js

    var gulp = require('gulp'),
        less = require('gulp-less'),
        minifyCSS = require('gulp-minify-css'),
        uglify = require('gulp-uglify'),
        concat = require('gulp-concat'),
        addsrc = require('gulp-add-src'),
        sourcemaps = require('gulp-sourcemaps');
    
    // CSS & Less
    gulp.task('css', function(){
        gulp.src('less/all.less')
            .pipe(sourcemaps.init())
            .pipe(less())
            .pipe(minifyCSS())
            .pipe(sourcemaps.write('source-maps'))
            .pipe(gulp.dest('public/css'));
    });
    
    // JS
    gulp.task('js', function() {
        gulp.src('resources/assets/bower/jquery/dist/jquery.js')
        .pipe(addsrc.append('resources/assets/bower/bootstrap/dist/js/bootstrap.js'))
        .pipe(addsrc.append('resources/assets/bower/blahblah/dist/js/blah.js'))
        .pipe(addsrc.append('resources/assets/js/my-script.js'))
        .pipe(sourcemaps.init())
        .pipe(concat('all.js'))
        .pipe(uglify())
        .pipe(sourcemaps.write('source-maps'))
        .pipe(gulp.dest('public/js'));
    });
    
    gulp.task('default',['css','js']);
    

    Note: jQuery and Bootstrap added for demonstration purposes of order. Probably better to use CDNs for those since they are so widely used and browsers could have them cached from other sites already.

提交回复
热议问题