If you've some strict (ordered!) arguments, then you can get them simply by checking process.argv
.
var args = process.argv.slice(2);
if (args[0] === "--env" && args[1] === "production");
Execute it: gulp --env production
...however, I think that this is tooo strict and not bulletproof! So, I fiddled a bit around... and ended up with this utility function:
function getArg(key) {
var index = process.argv.indexOf(key);
var next = process.argv[index + 1];
return (index < 0) ? null : (!next || next[0] === "-") ? true : next;
}
It eats an argument-name and will search for this in process.argv
. If nothing was found it spits out null
. Otherwise if their is no next argument or the next argument is a command and not a value (we differ with a dash) true
gets returned. (That's because the key exist, but there's just no value). If all the cases before will fail, the next argument-value is what we get.
> gulp watch --foo --bar 1337 -boom "Foo isn't equal to bar."
getArg("--foo") // => true
getArg("--bar") // => "1337"
getArg("-boom") // => "Foo isn't equal to bar."
getArg("--404") // => null
Ok, enough for now... Here's a simple example using gulp:
var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");
var env = getArg("--env");
gulp.task("styles", function () {
return gulp.src("./index.scss")
.pipe(sass({
style: env === "production" ? "compressed" : "nested"
}))
.pipe(rename({
extname: env === "production" ? ".min.css" : ".css"
}))
.pipe(gulp.dest("./build"));
});
Run it gulp --env production