The way to shim modules relying on `window`, `window.jQuery` and `document`

I was migrating a site to webpack and encountered a problem similar to the one discussed here at https://gitter.im/webpack/webpack/archives/2014/07/23 by @mathieumg , which was a dependency on window.jQuery.

My problem was that one of my dependencies (to be specific: https://github.com/eternicode/bootstrap-datepicker ) depended on window, window.jQuery and document.defaultView.

After a lot of trial and error, eventually I figured out a way combining externals , imports-loader and ProvidePlugin:

In webpack.config.js:

// Only the relevant part
{
    output: {
        libraryTarget: "var"
    },
    externals: [
        {
            "window": "window"
        }
    ],
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]  
}

In my entry js:

    var window = require("window");
    window.jQuery = jQuery;

    require("imports?this=>window!bootstrap-datepicker");
    require("imports?this=>window!bootstrap-datepicker.zh-CN");

Here I share my discovery and wonder whether there’re other approaches and whether this is the best practice of shimming such kind of libraries.

Author: Fantashit

1 thought on “The way to shim modules relying on `window`, `window.jQuery` and `document`

  1.     externals: [
            {
                "window": "window"
            }
        ],

    has no effect unless you require("window").


    You could try this with the newest webpack version:

            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
                "window.jQuery": "jquery"
            })

Comments are closed.