The expose-loader
loader allow you to expose module to global
object (self
, window
and global
).
To begin, you'll need to install expose-loader
:
$ npm install expose-loader --save-dev
Then add the loader to your webpack
config. For example:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js/i,
loader: 'expose-loader',
options: {
expose: '$',
},
},
],
},
};
And then require the target file in your bundle's code:
src/entry.js
require('expose-loader?expose=libraryName!./thing.js');
And run webpack
via your preferred method.
For example, let's say you want to expose jQuery as a global called $
:
require('expose-loader?expose=$!jquery');
Thus, window.$
is then available in the browser console.
Alternately, you can set this in your config file:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve('jquery'),
loader: 'expose-loader',
options: {
expose: '$',
},
},
],
},
};
Let's say you also want to expose it as window.jQuery
in addition to window.$
.
For multiple expose you can use !
in loader string:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve('jquery'),
rules: [
{
loader: 'expose-loader',
options: {
expose: ['$', 'jQuery'],
},
},
],
},
],
},
};
The require.resolve
call is a Node.js function (unrelated to require.resolve
in webpack processing).
require.resolve
gives you the absolute path to the module ("/.../app/node_modules/jquery/dist/jquery.js"
).
So the expose only applies to the jquery
module. And it's only exposed when used in the bundle.
Please take a moment to read our contributing guidelines if you haven't yet done so.