How to define system environment variables with RequireJS

When developing client applications in the past, I've always used some kind of server side application to package and serve JavaScript. This allowed me to pass environment variables to a client that varied between dev and dev environments.

I am working on a pure client application using RequireJS and serving it with a static web server. Some of the configuration depends on whether the application is running locally in development or in production (i.e. the URL of the server to which it will handle AJAX requests).

What's the best way to define the current environment using RequireJS?

+3


source to share


2 answers


// you can store two configs in two separate files
// FILE NAME: config-development.json:
// FILE CONTENT: {"url":"http://localhost:8000"}
// FILE NAME: config-production.json:
// FILE CONTENT: {"url":"http://google.com"}

// then load correct one and save it to variable
var config = getConfig();

function getConfig() {
  // if you pass ?dev=true to your url address default config that will be used is `config-development`
  // otherwise - `config-production`
  var configName = getParameterByName('dev', false) ? 'config-development' : 'config-production';

  window._config || (window._config = {});

  // for production version you should concat your config with main script or put it above main script
  // inside global `_config` variable for example
  if (window._config[configName]) return window._config[configName];

  // for development version you can just make an ajax call to get the config
  $.ajax({
    url : 'app/' + configName + '.json',
    async : false,
    success : function(response) {
      window._config[configName] = response;
    }
  });
  return window._config[configName];
}

// helper
function getParameterByName(name, defaults, location) {
  location = location || window.location.href;
  name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
  var result = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(location);
  return result === null ? defaults : decodeURIComponent(result[1].replace(/\+/g, ' '));
}

// usage
console.log(config.url); // `http://localhost:8000` for development env
                         // `http://google.` for production env

      



+1


source


Another approach I found uses the RequireJS config directly. Since RequireJS 1.1, you can include arbitrary configuration values. In my main config I set env: 'development

'and during build (with r.js) I set the value 'production'

.

I created a directory config

containing two files: development.js

and production.js

. Loading the corresponding file can be done using the Require plugin (we'll call it env

):

define(function() {

    return {
        load: function(name, req, load, config) {
            if (!config.env || config.isBuild) {
                config.env = 'production';
            }

            var path = name + '/' + config.env;
            req([path], function(mod) {
                load(mod);
            });
        }
    };

});

      



This is how I use it:

var config = require('env!config');

      

+3


source







All Articles