13

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the insertion to the .js file is more complex than it should be because I don't like Jetbrains to then alert me about all sorts of unnecessary stuff (like semi-colon or whatever). Also @echo has had some issues for me, so I manually output the closing ; semi-colon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.