Webpack: how to make angular auto-detect jQuery and use it as angular.element instead of jqLite?
Got this answer from john-reilly:
The mysterious case of webpack angular and jquery
bob-sponge's answer is not quite right - the Provide plugin is actually doing a text replacement on modules it processes, so we need to provide window.jQuery
(which is what angular is looking for) and not just jQuery
.
In your
webpack.config.js
you need to add the following entry to your plugins:
new webpack.ProvidePlugin({ "window.jQuery": "jquery"}),
This uses the webpack ProvidePlugin and, at the point of webpackification (© 2016 John Reilly) all references in the code to window.jQuery will be replaced with a reference to the webpack module that contains jQuery. So when you look at the bundled file you'll see that the code that checks the
window
object forjQuery
has become this:
jQuery = isUndefined(jqName) ? __webpack_provided_window_dot_jQuery : // use jQuery (if present) !jqName ? undefined : // use jqLite window[jqName]; // use jQuery specified by `ngJq`
That's right; webpack is providing Angular with jQuery whilst still not placing a
jQuery
variable onto thewindow
. Neat huh?
!!Update
Apparently you still need to use the commonJs require for angular in the ES6 example.
import $ from "jquery"window.$ = $;window.jQuery = $;var angular = require("angular");
below is the original answer
I want to purpose a easier solution. Just make jQuery a window global so that angular can recognize it:
var $ = require("jquery")window.$ = $;window.jQuery = $;var angular = require("angular");
or in your case (OUT DATED):
import $ from "jquery"window.$ = $;window.jQuery = $;import angular from "angular";
I hope this helps :)
In your case is better to use ProvidePlugin. Just add this lines to your webpack config in plugins section and jquery will available in your app:
new webpack.ProvidePlugin({ "$": "jquery", "jQuery": "jquery" })