Fidel90 Fidel90 - 7 months ago 140
Javascript Question

How to include jQuery in AngularJS when using browserify?

I'm using node, gulp and browserify to get my JS-Files into the right order and manage modules. I have jQuery and AngularJS installed as node modules and require them when needed. Angular by default uses jqLite to handle DOM-Elements.

I know that when jQuery gets loaded before AngularJS, Angular will use jQuery instead of jqLite.

But how is it possible to get Angular to use jQuery when using browserify. Or: How may one require jQuery to angular?

Now I'm just doing

var $ = require("jquery");
and use it when I need it. But I'd like to have an Angular that will natively give me jQuery methods when doing for example:

app.directive("dir", function () {
return {
link : function ($scope, $elem) {
var a = $elem.width();//jQuery methods currently not available here
}
};
});


What I actually need to do:

var jQuery = require("jquery");

app.directive("dir", function () {
return {
link : function ($scope, $elem) {
var jqElement = jQuery($elem);
var a = $jqElement.width();//jQuery methods are available here
}
};
});

Answer

You can use browserify-shim

npm install browserify-shim --save-dev

package.json

"browserify": {
  "transform": ["browserify-shim"]
},
"browser": {
  "jquery": "./node_modules/jquery/dist/jquery.js",
},
"browserify-shim": {
  "jquery": "$",
  "angular": {
    "exports": "angular",
    "depends": ["jquery"]
  }
}
Comments