Webpack and external libraries

JavascriptRequireCommonjsWebpack

Javascript Problem Overview


I’m trying out webpack (http://webpack.github.io/) and it looks really nice, however I’m kind of stuck here.

Say that I’m using a CDN for a library, f.ex jQuery. Then in my code, I want the require('jquery') to automatically point to the global jquery instance, instead of trying to include it from my modules.

I’ve tried using plugins like the IgnorePlugin:

new webpack.IgnorePlugin(new RegExp("^(jquery|react)$"))

This works for ignoring the library, but it still says that the required module is "missing" when I run the webpacker.

Somehow I need to tell webpack that jquery should be picked up from the global context instead. Seems like a common use case, so I’m kind of surprised that the docs doesn’t target this specifically.

Javascript Solutions


Solution 1 - Javascript

According to the Webpack documentation, you can use the externals property on the config object "to specify dependencies for your library that are not resolved by webpack, but become dependencies of the output. This means they are imported from the enviroment while runtime [sic]."

The example on that page illustrates it really well, using jQuery. In a nutshell, you can require jQuery in the normal CommonJS style:

var jQuery = require('jquery');

Then, in your config object, use the externals property to map the jQuery module to the global jQuery variable:

{
    externals: {
        // require("jquery") is external and available
        //  on the global var jQuery
        "jquery": "jQuery"
    }
}

The resulting module created by Webpack will simply export the existing global variable (I'm leaving out a lot of stuff here for brevity):

{
    1: function(...) {
        module.exports = jQuery;
    }
}

I tried this out, and it works just as described.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid HellsingView Question on Stackoverflow
Solution 1 - JavascriptGarrettView Answer on Stackoverflow