Diode Dan
Diode Dan

Reputation: 5141

Grunt.js for Angular.js dependency injection management

I am using Grunt to automatically build my web app. I have run into an interesting issue. I have two options: 1)grunt:dev and 2)grunt:build

grunt:dev just does basic tasks related to development. My "main" Angular module looks like this:

var myApp= angular.module('myApp', [
                                "ui.router",
                                "ui.bootstrap",
                                "someDependency",
                                "someDependency2" 
                                ]);

When I want to build, I do grunt:build. I am using the html2js grunt plugin to prime the Angular cache. However, this method generates a new module not in my development workflow called templates-main.

In order for this to work, when I build, I need the "main" module to look like:

var myApp= angular.module('myApp', [
                                "ui.router",
                                "ui.bootstrap",
                                "templates-main", //<<< NEW DEPENDENCY
                                "someDependency",
                                "someDependency2" 
                                ]);

Is there a recommended way of accomplishing this? If you include the dependency, but it is not there, it causes an Angular error. I am hoping this can be automated with Grunt.

Thanks in advance

Upvotes: 3

Views: 1308

Answers (2)

Diode Dan
Diode Dan

Reputation: 5141

I figured out a workaround for this. I am using Grunt's Concat module. This allows you to have a custom process system with regular expressions:

build: {
    options: {
        process: function(src, filepath) {
            return src.replace(/[/*<%]{4}.*[%>*/]{4}/g, '"templates-main",');
        }
    },
    src: ['src/app/app.js', 'src/app/**/*.js'],
    dest: 'build/app.js'

}

I then did the following in the code:

var eeApp = angular.module('eeApp', [
                                "ui.router",
                                "ui.bootstrap",
                                /*<% templates-main %>*/
                                "dashboard"
                                ]);

In normal use, the block comment will prevent the code from throwing an error. When the template process goes through, the regular expression will match the entire comment block and substitute in the required dependency. Nice!

Upvotes: 1

Lajos Veres
Lajos Veres

Reputation: 13725

I think the easiest way is to create an empty fake module file for your dev build and overwrite it with the real template cache in the production build.

This way you shouldn't change the dependencies dynamically.

(Or you can copy this file with grunt as well in the development setup, if you wouldn't like to overwrite originals.)

Upvotes: 0

Related Questions