I've split my gulpfile.js
into several files in a /gulp
folder to organize the code a little better. But now I want to pass a variable debug (boolean)
into the files that will switch behaviour of the gulp command being included (eventually I will use command-line arguments, but for now I just want to make it work with a variable).
The way I've got this setup, using a method I saw in a yeoman angular/gulp package, is using an npm module called require-dir
(which loads all *.js files in the /gulp
folder, where each has a set of gulp tasks that are set).
gulpfile.js:
var gulp = require('gulp'),
run = require('run-sequence'),
debug = true;
require('require-dir')('./gulp');
gulp.task('default', ['build', 'server', 'watch', '...']);
Which would load something like...
gulp/build.js:
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
...;
gulp.task('build', function () {
console.log(debug);
});
So when I run command gulp
, which runs the default
task, it will load build.js and then execute the build
gulp task. But unfortunately, it seems that debug
returns undefined.
How could I get this to work?
I was looking at using just module.exports()
and node's require()
method, but I couldn't figure out how to get the gulp task inside the included file to declare, so that it could then be run from the main gulpfile.js
file (in the desired sequence).
Can anyone offer some assistance? Thanks
The normal module way, really. Just change that gulp/build.js
file from not actually exporting anything to a proper require-able module:
module.exports = function(debug) {
"use strict";
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
...;
gulp.task('build', function () {
console.log(debug);
});
};
and then call it in your main file as:
...
var loadGulp = require('require-dir/gulp');
...
var debug = true;
loadGulp(debug);
I just create one object with all variables in it that I export as a module so I can use it throughout all my task files. For example
js/tasks/variables.js
module.exports = {
myBool: true
};
js/tasks/sass.js
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
log = $.util.log,
vars = require('./variables');
gulp.task('sass', function () {
log('myBool: ' + vars.myBool); // logs "myBool: true"
vars.myBool = false;
});
js/tasks/build.js
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
log = $.util.log,
vars = require('./variables');
gulp.task('build', function () {
log('myBool: ' + vars.myBool); // logs "myBool: false"
});
/gulpfile.js
Then you can get/set those variables from anywhere:
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
runSequence = require('run-sequence'),
vars = require('./js/tasks/variables'),
requireDir = require('require-dir')('./js/tasks');
gulp.task('production', function(){
runSequence('sass', 'build');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With