toy
toy

Reputation: 12161

How to inject variables to Javascript based on environment?

I'm building a javascript application and basically I have three different environments. Local, CI and QA environments. My back-end service is always going to be deployed separately to my front-end application. So, most of the Ajax calls are going to be CORS. We solved this problem already. However, in my code there's something like this.

jQuery.ajax({"url":"http://www.somecompany.com/api"});

So the problem is going to be in CI and QA environments which ajax calls will hit http://ci.somecompany.com/api and http://qa.somecompany.com/api or even http://test.somecompany.com/api. How do I inject those variables based on the environment I'm running. If it's Java or .NET I could use YAML and everything would be ok. But as Javascript it's client-side how do we choose which url to hit based on environments without find and replace in the code or some hacky way. What do people do to overcome this kind of problem generally?

Just a side note, I'm using Knockout.js

Upvotes: 1

Views: 1307

Answers (2)

Michal Jezierski
Michal Jezierski

Reputation: 69

If you build your application with grunt then use grunt-variablize. Put your configuration into resources/config.json

{
  "test": {
    "apiUrl": "http://test.somecompany.com/api"
  },
  "prod": {
    "apiUrl": "http://www.somecompany.com/api"
  }
}

configure variablize task:

grunt.initConfig({
  /* ... */
  variablize: {
    target: {
      input: "resources/Config.json",
      output: "dist/Config.js",
      variable: "Config",
      property: grunt.option('profile')
    }
  }
});

run grunt --profile=test, and use it this way:

$(document).ready(function(){
  var myURL = Config.apiUrl;
}); 

Upvotes: 2

Konza
Konza

Reputation: 2173

This might not be the best way to do it. But this works. :)

You can set value to a javascript variable with your server side code itself.

$(document).ready(function(){
   var myURL = "<%=urlFromServer%>"; //Assuming you are using JSP <%= ..%>
});

This global variable holds the value. You can re use this variable wherever you need it.

Upvotes: 0

Related Questions