I am trying to concatenate all plugins js files into one, by referencing an external file named config.php which stores all of the required scripts.
However while doing that, encountered a problem as gulp.src function will run first with the empty array "arrayFiles" before fs.readFile finish reading the file and update the array.
Some codes are shown below
// gulp.js
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var fs = require("fs");
var arrayFiles = new Array();
gulp.task('compressAllPlugins', function(done) {
fs.readFile('path/to/config.php', {encoding: 'utf-8', flag: 'rs'}, function(e, data) {
if (e) return console.log(e);
// codes to process content and convert it into array
// arrayFiles.push(eachData);
}
console.log('arrayFiles: ',arrayFiles);
gulp.src(arrayFiles)
.pipe(plugins.uglify().on('error', standardHandler))
.pipe(concat('myplugins.min.js'))
.pipe(gulp.dest('public/app'))
.on('end', done);
});
});
Below code shows the content of config.php
// config.php
<?php
return [
'scripts' =>[
'assets/libs/jquery/dist/jquery.min.js',
'assets/libs/angular/angular.js',
'assets/libs/angular-ui-router/release/angular-ui-router.min.js'
]
];
From the above code, console.log gives the correct array of data as shown:
// output
arrayFiles: ['assets/libs/jquery/dist/jquery.min.js',
'assets/libs/angular/angular.js',
'assets/libs/angular-ui-router/release/angular-ui-router.min.js']
However myplugins.min.js is not generated based on the array.
Question: How to make gulp.src runs AFTER fs.readFile updated arrayFiles? or any other way to workaround?
Attempts:
hardcode arrayFiles within the gulp.task and not using fs.readFile will read the respective files as inserted into the array.
// gulp.js (attempt #1)
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var fs = require("fs");
var arrayFiles = new Array();
gulp.task('compressAllPlugins', function(done) {
arrayFiles =[
'public/assets/libs/jquery/dist/jquery.min.js',
'public/assets/libs/angular/angular.js',
'public/assets/libs/angular-ui-router/release/angular-ui-router.min.js'
];
gulp.src(arrayFiles)
.pipe(plugins.uglify().on('error', standardHandler))
.pipe(concat('myplugins.min.js'))
.pipe(gulp.dest('public/app'))
.on('end', done);
});
});
This code able to generate myplugins.min.js as required with all the globs but it is not reading my config.php file.