Development / test / production variables in Javascript
I am trying to find the best approach for managing different values for the same variables in Devlopment, Test and Production environments.
For example, I have a variable jsonFile
that can be:
var jsonFile = http://localhost:63342/json/appsconfig.json
for env development
var jsonFile = http://192.168.35.59/applications/json/appsconfig.json
to check env
var jsonFile = http://example.com/applications/json/appsconfig.json
for env production
I'm trying to learn a lot about the Frontend Development Stack, but I'm confused as to which tool to use. I will be using Google Closure Tools for minification, might it be helpful to toggle variable values as well? Or can this be considered a Grunt task (even though I can't figure out how to properly set up Grunt tasks ...)?
source to share
What better way is to write JSON to JS file which is part of your build artifacts. Something like file-creator that can write a file like this (using a simplified setup that can obviously be made more dynamic).
At the top of your module.exports for grunt tasks, load the config file into var, e.g .:
var configData = grunt.file.readJSON('../config/appsconfig.json'),
Then write to a new JS file using the grunt file creator module
"file-creator": {
'dev': {
'build/config.js': function (fs, fd, done) {
fs.writeSync(fd,
'var yourSiteHere = yourSiteHere || {}; yourSiteHere.config = '
+ JSON.stringify(configData) + ";"
);
done();
}
}
}
Then load that JS file into the page (maybe even minify it using a separate task). Then you can access the configuration data like this:
var apiEndPoint = yourSiteHere.config.api.apiEndPoint,
apiKey = yourSiteHere.config.api.apiKey;
source to share