I'm a little confused on the various ways webpack allows to expose a variable that isn't available on npm or to be put in the bundle. I was able to expose the google visualizations chart script's global google var by using
resolve: {
extensions: ['.js', '.json'],
alias: {
'google': path.resolve(__dirname, 'vendor', 'google.js')
}
}
combined with
plugins: [
new webpack.ProvidePlugin({
'google': 'google'
})
]
however looking at the webpack docs there a couple other ways to shim, which look like they might do something similar. There is imports-loader and exports-loader, and script-loader. I know that I've linked to the docs, but I still find their descriptions of when these four should be used a bit unclear.
Also looking at this example, is this require not assigned to a variable? Where is it meant to go? And where is the documentation on what is going on with this syntax?
require("imports?$=jquery!./file.js")
scripts-loaderI never used this myself, but the idea is simple I guess. I think it can be used if for some reason you want to inject a script or a function or something in one of the modules/files you have no control over them.
imports-loader&exports-loaderIn one of the apps I worked on we had to use
tinymcewhich in its older versions was dependent onthisbeing alwayswindowbecause it was built to work as a global script. Not as a CommonJS or ES module.So in order to fix that, we had to use the
import-loaderso it can injectwindowto the script. Here how it looked like inwebpack.config.jsWhich says inject
windowin place ofthis& also we are usingexports-loaderhere so we can export the globaltinymceas a default export namedtinymceso we can use it as a normal module in our app.Thankfully all of this is already fixed in the latest releases.
ProvidePluginIn my experience, this is useful when a library is depending on another library being in a global scope or something. Like jQuery plugins for example, they do use one of these
$,window.$,jQuery&window.jQuerySo what this plugin will do is to make sure when
webpacksees one of these variations it will provide the jQuery object to it instead.The difference between this &
imports-loaderfor example that you might not know which variation is used by which script. So you letwebpackhandle this while theimports-loaderis kind of more specific.I hope this helped you a bit to understand the differences between all of them, also this is the new documentation page which I think better than the one you were checking https://webpack.js.org/guides/shimming/