Introduction
Recently I have moved my angularjs project from bower to npm. There were two reasons for that -
- Bower has started suggesting to use yarn or npm
- Not all packages are available on bower.
So I thought, its good time to move away from bower and start using npm as new package manager for my project. But moving away from bower and using npm is not straight forward and thats the motivation behind this post.
Application setup
For the sake of simplicity, we will be developing a very small angularjs application which displays current time. As we go along, I will be explaining why we need bowserify.
Full source code can be found at gulp-browserify-setup-angularjs
Folder Stuctureapp
folder will host our angularjs modules and controllers.
package.json
You can start with npm init
and add below dependencies.
Use npm install
to install all the dependencies.
|
|
For such a small application we don’t need momentjs. But to showcase more than one vendor library, we will be using momentjs.
Code
index.htmlsrc/index.html
file will have module and controller bindings along with placeholders to inject vendor and source scripts.
If you look at the html file, we are not adding any script right now. It will be injected by gulp-inject
plugin.
mymodule.jssrc/app/mymodule.js
file will have angularjs module myapp
.
mycontroller.jssrc/app/mycontroller.js
file will have controller myctrl
.
We have injected $interval
service to update our time after every 1 second.
vendor.js
Since we are not adding any scripts directly to out index.html
file, we will be adding our dependencies in src/vendor.js
file.
Here angular
and moments
are being searched from node_modules/
using node’s module lookup algorithm.
Browsers dont’t understand require
, and thats why we need browserify here.
Browserify lets you require(‘modules’) in the browser by bundling up all of your dependencies.
Gulp
Gulp is a javascript task runner same as Grunt.
Gulp is more of code based unlike config based Grunt.
We are going to few tasks in gulp. Create new file gulpfile.js
in our root folder.
Full source code can be found at gulp-browserify-setup-angularjs/gulpfile.js
task ‘build-vendor’build-vendor
task will take src/vendor.js
file as input and bundle all dependencies into dist/vendor.js
from a recursive walk of the require()
graph.
Basically it concatinates angular
and moment
code into dist/vendor.js
file.
|
|
task ‘build-js’build-js
task will copy all .js
files in app
folder to dist/js/
.
|
|
task ‘build-html’
Copy index.html
to dist
.
task ‘inject’
Now that we have vendor.js
and all source code .js
files copied to dist
, we need to inject them in our dist/index.html
file.
|
|
And finally write one task to club all of them together.
Run gulp build
.
This will build you code in dist
folder.
You can use your favourite http server to test. I am using http-server.