detect-environment
Version:
Detect environments in JavaScript similar to the way Laravel does
87 lines (67 loc) • 2.46 kB
Markdown
# Automatically set environment
Instead of having to pass in an `--env=foo` flag for every time you run a task
in gulp such as:
```sh
$ gulp release --env=production
```
If you pull in the [yargs](https://github.com/chevex/yargs) package this can
be determined automatically. We achieve this by accessing [`argv._`](https://github.com/chevex/yargs#and-non-hyphenated-options-too-just-use-argv_).
When a command is executed, any non hyphenated arguments will be added to the
`argv._` Object. For example,
```js
// foo.js
var argv = require('yargs').argv;
console.log(argv._);
```
Above we just defined a simple script to be consumed by the node cli. Running
this script will yield the comment below it.
```sh
$ node ./foo.js bar baz --qux
# ['bar', 'baz']
```
This approach can be applied to our `gulpfile.js`. The behaviour we want is to
simply run the command below, and have it switch to the `production`
environment.
```sh
$ gulp release
```
To achieve that we are going to pull in the `yargs` package and access the
`argv._` Array. The first value of that Array is saved to a variable named
`task`. Now, from within the `de()` callback, we simply check if `task` is equal
to the command that we want respond to. An example `gulpfile.js` has been
provided below.
```js
// gulpfile.js
// Pull in `gulp` and its plugins.
var gulp = require('gulp');
var gif = require('gulp-if');
var uglify = require('gulp-uglify');
// Pull in the `detect-environment` plugin.
var de = require('detect-environment');
// Determine the name of the task that was run.
var task = require('yargs').argv._[0];
// Determine our environment name and fetch its data.
var env = de(function (envName) {
if (task === 'release') {
return 'production';
}
return envName;
});
// Here we utilise the `gulp-if` plugin to conditionaly run the `gulp-uglify`
// plugin. The condition that we are tracking is whether or not we are in the
// `production` environment.
gulp.task('js', function () {
return gulp.src('src/**/*.js')
.pipe(gif(env.base, uglify()))
.pipe(gulp.dest('dist');
});
// Here we wrap the `js` task so that we automatically set the environment to
// `production` without having to specify `--env`.
gulp.task('release', ['js'], function (done) {
console.log('Release complete');
done();
});
```
This `gulpfile.js` allows us to run the `uglify()` plugin only when we are
*releasing* the codebase.