Concatenating Your Javascript with grunt-contrib-concat

Aaron Frost
InstructorAaron Frost
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 6 years ago

You can use Grunt to combine all of your Javascript files into a single concatenated file.

Man 1: [00:00] For our first task, let's go ahead and concatenate all of our JavaScript into one file. We're going to use a Grunt plug-in called Grunt Concat, which will take all of our JavaScript and put it into one file.

[00:10] Let's start by installing the Grunt Concat plug-in. In a terminal type MPM install grunt-contrib-concat and use the save-dev flag so that it adds it to your package.json.

[00:24] Now that it's added and we have it on the screen, let's go ahead and configure it in our grunt file. We start by loading it. We'll say, "Grunt contrib concat."

[00:35] We'll add a concat option to our net.config. Let's give it a JavaScript target so that we can target different sections later on if we need to.

[00:43] Inside the JavaScript target, we're going to give it two pieces of information. The first one is source, which is an array of JavaScript files that we want it to take. The second one is the destination. This is where we want it to put all the files that it's going to concatenate into one.

[01:00] The destination, we're going to go ahead and make a build directory. We want it to put all of our JS into one file called build\app.js. Now we need to tell it which files we want it to concatenate.

[01:11] It's important that the very first file that we use is the angular.js file. The reason we want to do this is because all of our other files depend on a global Angular object so we need to load Angular first.

[01:23] The second file we want to load is our app.js because that's the file that declares our module. After that we'll just use a wildcard syntax that will pick up all of the rest of our JavaScript files.

[01:35] It's important to note that this pattern matches our app.js and our angular.js files but one of the cool things about Grunt is that it won't pick those up if we explicitly named them ahead of time.

[01:46] Now that we've got this configured, from the terminal we can go ahead and run Grunt Concat and it will take all of our JavaScript and put it into one entry inside this build directory. That's how easy it is to concatenate all your files.

[01:59] The next step is minifying them now that they're all into one file.