Webpack and external libraries
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.
Solution 1:
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.