Auto-include JavaScript Files to your main HTML file with Grunt

If you use AngularJS or any other MVC which promotes code modularity and separation of concerns, you will likely have a LOT of JavaScript files floating around. In order for your application to work properly, you will have to include each JS file one by one. In the beginning of your project, this may seem manageable, but as your project grows and grows with more files, and bower components, it will save you a lot of time and headache to have them added automatically!

Enter Grunt. Grunt is a JS task runner that does a lot of neat things for you like concatenating, uglifying and linting JS files, and minifying CSS files to name a few common tasks. Let’s see how we can configure this to make our lives easier! **If you have never used Grunt before, I suggest going to the official Getting Started guide.

After we have Grunt installed, we want to install the dependencies we will use. We will be using grunt-include-source. Install this via NPM like so:

npm install grunt-include-source --save-dev

In our Gruntfile, we have to load our tasks.

Next we want to set up our task configurations inside of our grunt.initConfig function so we can tell Grunt how we want them to run. We will start with includeSource.

Your basePath is where includeSource will look for your files at. You can set up your templates for how the script and link tags will be included in your HTLM file here as well.

‘myTarget’ (you can name this anything) specifies the template you will use(on the right of the colon), and which file the scripts will be included in (on the left).

I decided to put the template and index.html file in the same directory. The template is almost exactly like your regular html file. The difference is you include comments which includeSource reads and uses to add the sources to your HTML file. This is how my template looks.

Now I can register a grunt task, so that every time I call it, it will add the JS files I need.

In the terminal, in the root directory of my folder, I type in “grunt build” and BLAMMO!

BLAMMO!

Obviously, running “grunt build” in the terminal every time isn’t optimal, but you can set up a watch task via grunt-contrib-watch to check for whenever you add or delete a file and update the index.html file. You can also use grunt-wiredep to include all of your bower component files. But more on those later! Hope this helps to automate your life :)