Then you can use the expose-loader using two approaches.
Inline
The | or %20 (space) allow to separate the globalName, moduleLocalName and override of expose.
The documentation and syntax examples can be read here.
[!WARNING]
%20 is space in a query string, because you can't use spaces in URLs
import $ from "expose-loader?exposes=$,jQuery!jquery";//// Adds the `jquery` to the global object under the names `$` and `jQuery`
import { concat } from "expose-loader?exposes=_.concat!lodash/concat";//// Adds the `lodash/concat` to the global object under the name `_.concat`
import { map, reduce,} from "expose-loader?exposes=_.map|map,_.reduce|reduce!underscore";//// Adds the `map` and `reduce` method from `underscore` to the global object under the name `_.map` and `_.reduce`
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.
The | or %20 (space) allow to separate the globalName, moduleLocalName and override of expose.
String syntax - [[globalName] [moduleLocalName] [override]] or [[globalName]|[moduleLocalName]|[override]], where:
globalName - the name in the global object, for example window.$ for a browser environment (required)
moduleLocalName - the name of method/variable/etc of the module (the module must export it) (may be omitted)
override - allows to override existing value in the global object (may be omitted)
If moduleLocalName is not specified, it exposes the entire module to the global object, otherwise it exposes only the value of moduleLocalName.
src/index.js
import $ from "jquery";import _ from "underscore";
webpack.config.js
module.exports = { module: { rules: [ { test: require.resolve("jquery"), loader: "expose-loader", options: { // For `underscore` library, it can be `_.map map` or `_.map|map` exposes: "$", // To access please use `window.$` or `globalThis.$` }, }, { // test: require.resolve("jquery"), test: /node_modules[/\\]underscore[/\\]modules[/\\]index-all\.js$/, loader: "expose-loader", type: "javascript/auto", options: { // For `underscore` library, it can be `_.map map` or `_.map|map` exposes: "_", // To access please use `window._` or `globalThis._`
The name of method/variable/etc of the module (the module must export it).
If moduleLocalName is specified, it exposes only the value of moduleLocalName.
By default, loader does not override the existing value in the global object, because it is unsafe.
In development mode, we throw an error if the value already present in the global object.
But you can configure loader to override the existing value in the global object using this option.
To force override the value that is already present in the global object you can set the override option to the true value.