Set base URL in angularjs project based on the environment

Fedy2 picture Fedy2 · May 5, 2015 · Viewed 9.8k times · Source

I'm working on an AngularJs project created using Yeoman. The project uses Grunt as task manager.

In my index.html I need to set the base url:

<base href="/">

The href attribute value depends on the environment: if the environment is development I want href to be simply /, if the environment is production the value has to be something else a/b/c.

What are the available solutions to this problem?

It is possible to set it dynamically at runtime using a constant from AngualrJs or it is better to set it statically at build/serve time?

Answer

rpadovani picture rpadovani · May 5, 2015

Personally I prefer to set it a build/serve time, so I don't need to change the code when I change environment.

So, I can push on the server and use grunt serve:production - you don't need to change the code, so you can use git hooks and a bash script to easily serve your code.

To achieve this in Grunt you can use ngcostant. You define the vars you want, and it creates a file named config.js (or whatever you want) that exposes your vars under ENV (or whatever you want) using .configure()

Talking about your case, you can have something like this in your Gruntfile:

ngconstant: {
  options: {
    space: ' ',
    wrap: '"use strict";\n {%= __ngModule %}',
    name: 'config'
  },
  vagrant: {
    options: {
      dest: 'app/scripts/config.js'
    },
    constants: {
      ENV: {
        name: 'vagrant',
        baseUrl: 'http://192.168.33.99/api/v0',
      }
    }
  },
  test: {
    options: {
      dest: 'app/scripts/config.js'
    },
    constants: {
      ENV: {
        name: 'test',
        baseUrl: 'http://test.example.com/api/v0',
      }
    }
  },
}

Then, in your app you can take the baseUrl using ENV.baseUrl and expose to your html file, like this (angular):

app.run(function($rootScope, ENV.baseUrl){   
    $rootScope.baseUrl = config.baseUrl;
});

(html)

<base ng-href="{{baseUrl}}">

So you can serve your application using grunt serve:vagrant when you're using vagrant or grunt serve:test when you want to run on your test server