Reputation: 19760
I'm testing replacing Webpack 5 with esbuild. How do you export globals in a bundle? I have a single dependency, jQuery, but I will have more in the future. My esbuild script is:
// build.js
const esbuild = require('esbuild');
esbuild
.build({
bundle: true,
entryNames: "[dir]/[name].[hash]",
entryPoints: {
libs: "src/libs.js",
},
outbase: "src",
outdir: "dist",
platform: 'browser',
})
.catch(() => process.exit(1));
And the libs.js
that indicates dependencies to bundle is:
// src/libs.js
import 'jquery';
And here's my package.json
:
{
// ...
"dependencies": {
"jquery": "~3.6.0"
},
"devDependencies": {
"esbuild": "^0.14.23"
},
// ...
}
Running the build script will properly bundle jQuery in dist/libs.{hash}.js
but including this in a webpage via a script tag exposes neither window.$
nor window.jQuery
. How do I get these to export?
In Webpack 5, I would use expose-loader
to achieve this:
module.exports = {
module: {
rules: [
{
test: require.resolve('jquery'),
loader: 'expose-loader',
options: {exposes: ["$", "jQuery"]},
},
],
},
};
Upvotes: 3
Views: 4852
Reputation: 19760
In order to get this to work with esbuild, you have to import an object from the module, and set the object on window
. E.g.,
// Import module.
import * as module from 'module';
// Export module on window.
window.module = module;
jQuery exports the jQuery
object as the default value. To export it as a global you have to do:
// Import jQuery.
import {default as jQuery} from 'jquery';
// Which can be shortened to.
import jQuery from 'jquery';
// Then export jQuery.
window.$ = jQuery;
window.jQuery = jQuery;
Upvotes: 4