Search code examples
angularjsgruntjsdependenciesbuild-process

How can I declare dependencies in index.html with Grunt?


My AngularJS app is structured like this:

myproj
|-- app
|    |-- index
|    |     |-- index.html
|    |     |-- index.js
|    |-- page1
|    |     |-- page1.html
|    |     |-- page2.js
|    |-- page2
|-- common
|    |-- resources
|    |     |-- page1resources.js
|    |     |-- page2resources.js

index.html is my main page and contains ui-router which controls how pages are displayed. To get this to work I have to declare all of the dependencies in index.html, so I have a list of 20 .js files and a handful of style sheets.

It's a pain to manage these dependencies, and it takes me an extra two minutes or so each time I create a new page.

From what I've read it seems that Grunt would be able to simplify this task. However, it would be too time consuming for me at the moment to learn all about Grunt and the various tasks I can use for this.

How do you manage imports and dependencies in an AngularJS app with Grunt?


Solution

  • You are looking for Grunt wiredep

    Grunt has this awesome utility called wiredep, which does basically the things you want. It looks for .js files where you set it to look for, and injects it into your index.html file.

    A simple wiredep configuration in Gruntfile.js will be as follows :

    wiredep: {
    
      task: {
    
        // Point to the files that should be updated when
        // you run `grunt wiredep`
        src: [
          'app/views/**/*.html',   // .html support...
          'app/views/**/*.jade',   // .jade support...
          'app/styles/main.scss',  // .scss & .sass support...
          'app/config.yml'         // and .yml & .yaml support out of the box!
        ],
    
        options: {
          // See wiredep's configuration documentation for the options
          // you may pass:
    
          // https://github.com/taptapship/wiredep#configuration
        }
      }
    }
    

    Also, you can look into Yeoman, which has AngularJS generator for your project. Using this generator, you can inject new controllers, directives right from the CLI, without having to think about injecting them, which wiredep handles it for you.