Loading jquery before angular and DOMContentLoaded (angular and jquery)

Just for some brief background, angular by default will load it’s own jquery spinoff jqlite for DOM queries and manipulations, unless it sees jquery in which case it’ll use that instead. From the angular docs:

To use jQuery, simply load it before DOMContentLoaded event fired.

Recently I converted over my angular application to use webpack and this is one of the only things left I’ve been unable to solve. I haven’t found a way to have webpack load jquery prior to angular or prior to DOMContentLoaded for it to default to jquery. For the moment I’m just using $() to explicitly call jquery where I need to rather than relying on angular.element() which will fall back to jqlite. I was hoping the authors or any other heavy users of webpack would have some insight here as I’ve been unable to make this work on my own. Thanks.

Author: Fantashit

3 thoughts on “Loading jquery before angular and DOMContentLoaded (angular and jquery)

  1. The easiest way is probably to write require("jquery") before require("angular"). This will initialize the $-variable before angular tries to read it.

    A more generic approach which doesn’t rely on execution order is to inject the line var $ = require("jquery") before the angular-module. This way you can ensure, that jquery is always initialized before angular, regardless of where it has been required.

    Injecting variables or modules is done via the imports-loader. After running npm i imports-loader --save you can do:

    // webpack.config.js
    ...
    module: {
        loaders: [
            { test: /[\/]bower_components[\/]angular[\/]angular\.js$/,
                loader: "imports?$=jquery" } 
        ]
    }
  2. Ah, expose did the trick thanks!

    module: {
            loaders: [{
                test: /jquery-1\.10\.2\.js$/,
                loader: 'expose?jQuery'
            }
    

    Angular looks for window.jQuery specifically so the fact that I already had $ configured wasn’t having any affect.

Comments are closed.