March 2, 2014 . . Comments
Tags:


Using Environment configuration with Yeoman Angular Generator


I am using generator-angular and needed to inject environment variables. As it turns out it was really simple using grunt-ng-constant
To install ng-constant
npm install grunt-ng-constant --save-dev
We need to then add ngconstant to our Grunfile in the init section
// Define the configuration for all the tasks
grunt.initConfig({
    //...

    ngconstant: {
      options: {
        space: '  '
      },
      // Environment targets
      development: [{
        dest: '.tmp/scripts/config.js',
        wrap: '"use strict";\n\n <%= __ngModule %>',
        name: 'config',
        constants: {
          ENV: {
            name: 'development',
            foo: 'We are in development!'
          }
        }
      }],
      production: [{
        dest: '.tmp/scripts/config.js',
        wrap: '"use strict";\n\n <%= __ngModule %>',
        name: 'config',
        constants: {
          ENV: {
            name: 'production',
            foo: 'We are in production!'
          }
        }
      }]
    },
Make sure that you have the destination in production and development set to .tmp. I was facing problems that the config files where not generated properly.
For development look for this section and add the ngconstant:development
    grunt.task.run([
      'clean:server',
      'ngconstant:development',//add this
      'bower-install',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
And for build add ngconstant:production
  grunt.registerTask('build', [
    'clean:dist',
    'ngconstant:production',//add this
    'bower-install',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngmin',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'rev',
    'usemin',
    'htmlmin'
  ]);
In our index html we need to include the config file
<!--build:js({.tmp,app}) scripts/scripts.js -->
<script src="/scripts/app.js"></script>
<script src="/scripts/config.js"></script>
<!-- endbuild -->
If you now run grunt serve or grunt build this will generate following module
"use strict";

 angular.module("config", [])

.constant("ENV", "production")

.constant("apiEndpoint", "http://api.memoflo.com")

;
Inject the module into your app
angular.module('myApp', [
  'config'
])
Now whenever you require you can inject ENV as a dependency and use
angular.module('myApp')
  .controller('Ctrl', function (ENV) {
  alert(ENV.foo);
});
Happy coding!
 

Comments

Please feel free to leave any comments as long as they're related to the topic.