I'm using Restangular in a project built using Gruntjs. Here is a snippet:
// scripts/app.js
angular.module('myApp', ['restangular'])])
.config(['RestangularProvider', function(RestangularProvider) {
/* this is different on dev, test, prod environments */
var baseUrl = 'http://localhost:8080/sms-api/rest/management/';
RestangularProvider.setBaseUrl(baseUrl);
}])
I would like to have a different value for baseUrl
if specified at cli or a default if not specified:
$ grunt server
Using default value for 'baseUrl'
$ grunt build --rest.baseUrl='http://my.domain.com/rest/management/'
Using 'http://my.domain.com/rest/management/' for 'baseUrl'
How can I do that?
It's possible with the aid of Grunt preprocess which is useful for replacing (and other things) templates inside files.
First add this to your .js code:
/* Begin insertion of baseUrl by GruntJs */
/* @ifdef baseUrl
var baseUrl = /* @echo baseUrl */ // @echo ";"
// @endif */
/* @ifndef baseUrl
var baseUrl = 'http://www.fallback.url';
// @endif */
/* End of baseUrl insertion */
Then in your grunt file, after installing grunt preprocess (i.e npm install grunt-preprocess --save-dev
you add the following configuration:
preprocess: {
options: {
context: {
}
},
js: {
src: 'public/js/services.js',
dest: 'services.js'
}
},
obviously, you need to update the js file list accordingly to which ever files you use. important notice - if you are planning on updating the same file (and not to a new destination) you need to use the inline option
At last, in order to work with a command line config variable
, add the following custom task to your grunt file as well:
grunt.registerTask('baseUrl', function () {
var target = grunt.option('rest.baseUrl') || undefined;
grunt.log.ok('baseUrl is set to', target);
grunt.config('preprocess.options.context.baseUrl', target);
grunt.task.run('preprocess');
});
Finally, run the baseUrl task like so:
grunt baseUrl --rest.baseUrl='http://some.domain.net/public/whatever'
Notice I put in a fallback url so you can also run grunt baseUrl
and grunt will set your baseUrl to your defined one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With