Concat scripts in order with Gulp

2022-08-30 01:29:32

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

How do I get it to concat the scripts so that they’re in order?

// JS concat, strip debugging and minify
gulp.task('scripts', function() {
    gulp.src(['./source/js/*.js', './source/js/**/*.js'])
    .pipe(concat('script.js'))
    .pipe(stripDebug())
    .pipe(uglify())
    .pipe(gulp.dest('./build/js/'));
});

I have the right order of scripts in my , but since files are organized by alphabetic order, gulp will concat after , and the order of the scripts in my does not matter, it looks at the files in the directory.source/index.htmlunderscore.jsbackbone.jssource/index.html

So does anyone have an idea on this?

Best idea I have is to rename the vendor scripts with , , to give them the proper order, but I am not sure if I like this.123

As I learned more I found Browserify is a great solution, it can be a pain at first but it’s great.


答案 1

I had a similar problem recently with Grunt when building my AngularJS app. Here's a question I posted.

What I ended up doing is to explicitly list the files in order in the grunt config. The config file will then look like this:

[
  '/path/to/app.js',
  '/path/to/mymodule/mymodule.js',
  '/path/to/mymodule/mymodule/*.js'
]

Grunt is able to figure out which files are duplicates and not include them. The same technique will work with Gulp as well.


答案 2

Another thing that helps if you need some files to come after a blob of files, is to exclude specific files from your glob, like so:

[
  '/src/**/!(foobar)*.js', // all files that end in .js EXCEPT foobar*.js
  '/src/js/foobar.js',
]

You can combine this with specifying files that need to come first as explained in Chad Johnson's answer.