Can we create environment variables for basic applications?

We are creating a basic application that uses a set of REST APIs. Ideally, we want to have different configuration files for dev and live, which are defined by environment variables. Is it possible.

Thanks in advance

+6
source share
3 answers

I recommend you have one file this way like this:

var YourProject = {}; YourProject.Config = { Local : { db : 'mysql:dumy: dummy@localhost ', relativeUrl : 'blabla', otherConfig : '123456' }, Dev : { db : 'mysql:dumy: dummy@localhost ', relativeUrl : 'blabla', otherConfig : '123456' }, Production : { db : 'mysql:dumy: dummy@localhost ', relativeUrl : 'blabla', otherConfig : '123456' } } 

And then in your scraps there is something like this:

 YourProject.ConfigHandler = { getValue : function(key){ var env; switch( window.location.hostname ){ case "localhost": case "127.0.0.1": env = 'Local'; break; case "dev.yourdomain.com": env = 'Dev'; break; case "yourdomain.com": env = 'Production'; break; default: throw('Unknown environment: ' + window.location.hostname ); } return YourProject.Config[env][key]; } }; 

This way, you will only have one file and for the URLs of the difference of the APIs for the conversation you will need to call only one line:

 YourProject.ConfigHandler.getValue( 'db' ); 
+11
source

Your question can target any javascript application, not just the base application, so the following answer is more general:

I have a config.js file, which is the first one loaded into your HTML. Content is just a configuration JSON object:

 var CONFIG = { debug : false, server : 'http://production.foo.com' }; 

Now each component of your application can access the configuration, since CONFIG is a global object. Therefore, you can write this anywhere in your application:

 if (CONFIG.debug) { console.log('my debug stuff...'); } 

The trick is to have 2 config.js files. One for development and one for production. When you want to publish your application, package the production.js file and upload it to your server.

You can create an assembly script to create your production application. As a first step, he could copy the correct config.js file to the right place. You can also add steps to minimize your js files, merge them into one file and much more.

+2
source

I adapted Daniel a good answer for Coffeescript / CommonJS, so in my config.coffee I have:

 env = switch window.location.hostname when "localhost", "127.0.0.1" "development" when "www.example.com", "example.com" "production" config = development: urlRoot: "http://localhost:3000" production: urlRoot: "http://www.example.com" module.exports = config[env] 

And then the client code looks like this:

 config = require("config") config.urlRoot 
+1
source

Source: https://habr.com/ru/post/920367/


All Articles