Webpack: how to make angular auto-detect jQuery and use it as angular.element instead of jqLite?

前端 未结 5 1011
甜味超标
甜味超标 2021-01-31 14:42

I\'m using Webpack to build an Angular 1.4 project. The project makes use of several jQuery plugins, which are wrapped into angular directives. Those directives internally use <

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 15:34

    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 for jQuery 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 the window. Neat huh?

提交回复
热议问题