mat.hudak
mat.hudak

Reputation: 3193

How to use environment variable in js file with gulp

I'm helping on the project consisting of html, css and js plugins all built with gulp. The project was bought as a template and customized by our marketing team (yep...) and I'm supposed to help with scripting.

Now there is a plugin which sends form data to server with $.ajax() call. Url param is set as a constant, like this:

$.ajax({
  url: 'exact-api-url',
  type: 'POST'
  ...
});

How can I replace it with env variable and where exactly should I store it? There are different URLs for prod and dev. I want it to look like this:

$.ajax({
  url: environment.API_URL,
  type: 'POST',
  ...
});

From solutions I found I got the feeling that they mostly deal with env variables within gulpfile.js itself not the js code in project. One workaround suggested using global js variables which I don't like. What's the proper way to do it?

I'm an an Angular/React guy, working mostly with webpack and I find gulp's lack of environment folder disturbing.

Upvotes: 1

Views: 5430

Answers (1)

santosh
santosh

Reputation: 575

Below is one of solution. You can generate a config file as config.js using template config.tmpl.js

module.exports = <%= url %>

Below are my gulp task to set the url for Dev & prod.

gulp.task('set-dev-node-env', function() {
    return process.env.url = 'exact-dev-url';
});

gulp.task('set-prod-node-env', function() {
    return process.env.url = 'exact-prod-url';
});

Task to generate the config file.

var gulp = require('gulp');
var template = require('gulp-template');
var rename = require('gulp-rename');

gulp.task('config', function() {
    return gulp.src('path/to/config.tmpl.js')
      .pipe(template({url: `${process.env.url}`}))
      .pipe(rename('config.js'))
      .pipe(gulp.dest('path/to/config.js'));
});

Below are task to build for dev and prod

gulp.task('build_for_prod', ['set-prod-node-env','config'], function() {
    runSequence(
        '...buildSteps'
    );
});

gulp.task('build_for_dev', ['set-dev-node-env','config'], function() {
    runSequence(
        '...buildSteps'
    );
});

and finally, in your JS file

var config = require('path/to/config.js');

$.ajax({
    url: config.url,
    type: 'POST',
    ...
});

Hope this helps :)

Upvotes: 2

Related Questions