detect-environment
Version:
Detect environments in JavaScript similar to the way Laravel does
101 lines (76 loc) • 2.4 kB
Markdown
# Using environment files
Here we look at an example to use `detect-environment` file parsing features to
generate tailored environment specific code. Given we have the two following
`.env.*` files:
```yml
# .env.yml
---
api: "http://api.website.com/v1/"
```
```yml
# .env.local.yml
---
api: "localhost:3333/v1/"
```
And the following example JavaScript file,
```js
// src/example.js
// We are in the "<%= env.name %>" environment
$.post('<%= env.data.api %>', {
'foo' : 'bar'
});
```
We then have enough information to generate environment specific code by
utilising [Lo-Dash's `_.template`](https://lodash.com/docs#template) function.
Here we are using `detect-environment` to generate a file that will hit a
hypothetical api. We can utilise the environment detection to either hit a copy
that we are running locally, or build a version of the file that is to be
consumed by the production environment.
This templating functionality is pulled in by using the [`gulp-template`](https://github.com/sindresorhus/gulp-template)
plugin. The only thing that the `detect-environment` plugin is providing is a
way to load conditional data.
An example `gulpfile.js` is provided below.
```js
// gulpfile.js
// Pull in `gulp` and its plugins.
var gulp = require('gulp');
var tmpl = require('gulp-template');
// Pull in the `detect-environment` plugin.
var de = require('detect-environment');
// Determine our environment name and fetch its data.
var env = de();
// Stamp out the `example.js` file with our environment data.
gulp.task('js', function () {
return gulp.src('src/example.js')
.pipe(tmpl({
'env' : env
}))
.pipe(gulp.dest('dist');
});
```
With our files now setup correctly we can kick off the gulp task.
```sh
$ gulp js
```
Because `detection-environment` defaults to a `local` environment when one is
not specified, you can see how the `dist/example.js` file is populated with data
from the `.env.local.yml` file.
```js
// dist/example.js
// We are in the "local" environment
$.post('localhost:3333/v1/', {
'foo' : 'bar'
});
```
And similarly if you were to pass in the `production` environment, the
`example.js` file will be compiled as shown below.
```sh
$ gulp js --env=production
```
```js
// dist/example.js
// We are in the "production" environment
$.post('http://api.website.com/v1/', {
'foo' : 'bar'
});
```