Setting environment variables in Angular using Grunt

I’ve come across an interesting problem recently. While developing an angular app, I needed to switch from a live web service to a local web service during the development. And this got me thinking: “This is the perfect situation where different environments would be incredibly useful”. Instead of manually changing the endpoints of the web service and remembering to switch them back again before deploying the new version, I could simply use one set of constants during development and another for deployment, making my life much easier.

Angular environments

Development vs production code in angular can be considered the app folder vs the dist folder. The app folder contains all your files and libraries, neatly organized in folders and properly named. The dist folder on the other hand contains only one script file (typically) with minified code containing ALL the scripts across your app, including libraries (quite cool, eh?). The dist scripts are not human-readable but pretty much identical to your app and much smaller in size, therefore more suitable for publishing.

Installing ng-constant

In order to use different environment variables with angular, I use a great Grunt task called ng-constant. This allows us to create dynamic modules in angular, that only contain constants retrieved from json files. This is how you include it in your Gruntfile.js (example usage).

Of course, you need to reference the newly generated file in your index.html, as well as including the new module in your app.js as a dependency. For a full list of changes that I did to include ng-constant, go here.

Setting up the environments

Assuming ng-constant is installed, we want to be able to set a set of constants to use throughout our app. These constants should be able to have different values during development and deployment. In order to do this, we need to create dev.json and prod.json files containing the constants. Save them somewhere appropriate in your app. Then create these tasks in your Gruntfile.js.

Make sure they use the same module name, the only difference we want between development and production are the variable values.


You can also use ng-connect for different purposes too, such as allowing users to specify user specific information (such as separate database connections) in a connections.json file. It is recommended that you git ignore these configuration files and save connections-example.json as a dummy file instead.

Use dev.json and prod.json to save only the variables that are different between environments. For the rest, you can use ng-constant to create common constants, in a file called common.js for instance.


And there you have it! You can now easily use environment specific constants within angular! Happy coding!

Further reading

Related posts

Comments are closed.