hjl
hjl

Reputation: 2802

How does browserify work with angular based app?

I was mess around this for a couple of days. I was trying to get browserfiy to work well with angular based app. I have tried following options but still cannot decide on a better way to do it, it will be appreciated if anyone can give any suggestion on this.

Bundle all angular related libs, like angular, angular-animate, angular-ui-router, etc into vendor.js by using bundle.require

Bundle all app reated source files into app.js by using bundle.external

That works fine in dev environment, all modules in vendor.js could be required from app.js

But it crashed in prod environment. The minified angular files are not all CMD. Although I can browserify-shim angular.min.js and bundle.require angular-ui-router.min.js, it's kind of cubersome to do this file by file.

Leave all angular libs into <script> and only output bundle for app files. That means in app.js, I have to refer to angular as a global var which is not good.

So what's the best practise to do this?

Upvotes: 0

Views: 227

Answers (1)

ryeballar
ryeballar

Reputation: 30098

Even if you do require() angularjs, it still exposes the angular namespace in the context of its environment (Window object for browsers). What I usually do is simply put all angularjs modules dependencies (e.g. ui.router, ngResource and etc) below the bundled(browserified) javascript where your angularjs application resides. In my case, I use gulp-useref to concatenate all the script provided by the gulp-inject tags(this includes scripts bundled by browserify).

As you may have noticed below, the bower components(bower:js tag) are added below the bundle(inject:js tag). Since requiring the angular module will attach the angular object in the window object, then any components external to browserify can access window.angular.

The answer I provided is somehow similar to option 2 but without the disadvantage of referring angular as a global variable within your browserified code.

e.g.

<!-- build:js({./.tmp,./}) js/index.js -->
<!-- inject:js -->
<!-- endinject -->
<!-- bower:js -->
<!-- endinject -->
<!-- endbuild -->

UPDATE:

I've create a github repo that resembles the answer provided above. Try to clone it, and see what you can do with it.

Upvotes: 1

Related Questions