Gulpfile.js for vanilla AngularJS projects

Since I’ve learnt Angular, most of my front-end web applications are written in it. Its brilliant. Everything works fine, up to a point where your application has grown 10 times the size it was since you started it. At some point you’d want something to accelerate your delivery. That’s when gulp comes in.

Gulp is kinda like a build tool but for javascript based applications. It runs on Node.js and is available on npm. All you need to do is:

Shell

1

npm install-ggulp

or if you are using a unix based application:

Shell

1

sudo npm install-ggulp

That gets you access to the gulp command line. Once you have gulp installed, you need to something that tells it what to do with your project. Unlike many other build tools, gulp favours code over configuration. This means that rather than writing XML or YAML files that define the tasks, you write code. This is what makes gulp unique.

So, here’s what I have. Below is my gulpfile.js that I use in most of my AngularJS projects:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

/**

* Created by manthanhd on 04/01/2016.

*/

vargulp=require('gulp'),

gutil=require('gulp-util'),

sourcemaps=require('gulp-sourcemaps'),

concat=require('gulp-concat'),

ngAnnotate=require('gulp-ng-annotate'),

watch=require('gulp-watch'),

uglify=require('gulp-uglify');

gulp.task('default',['build-js']);

gulp.task('build-js',function(){

returngulp.src(['public/app/**/*.js'])

.pipe(sourcemaps.init())

.pipe(concat('bundle.min.js'))

.pipe(ngAnnotate())

//only uglify if gulp is ran with '--type production'

.pipe(gutil.env.type==='production'?uglify():gutil.noop())

.pipe(gutil.env.type==='production'?gutil.noop():sourcemaps.write())

.pipe(gulp.dest('public/dist'));

});

gulp.task('watch',function(){

gulp.watch('public/app/**/*.js',['build-js']);

});

Most of my AngularJS code resides in public/app directory and hence you’ll see that in multiple places in that file.

A quick glance should tell you that this minifies all of my AngularJS code and combines it all in one big file called bundle.min.js which is then placed in public/dist folder. My HTML page is configured to only reference bundle.min.js.

When executed normally, it doesn’t minify the code because it assumes that the javascript code is being used for development. However, when I run gulp --type production it minifies the code and doesn’t write sourcemaps.