如何使用 esbuild 将全局变量导出到捆绑包中?
我正在测试用 esbuild 替换 Webpack 5。如何在捆绑包中导出全局变量?我只有一个依赖项 jQuery,但将来我会有更多依赖项。我的 esbuild 脚本是:
// 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));
指示捆绑依赖项的 libs.js
是:
// src/libs.js
import 'jquery';
这是我的 package.json
:
{
// ...
"dependencies": {
"jquery": "~3.6.0"
},
"devDependencies": {
"esbuild": "^0.14.23"
},
// ...
}
运行构建脚本将在 中正确捆绑 jQuery dist/libs.{hash}.js
但通过脚本标记将其包含在网页中既不会公开 window.$
也不会公开 window.jQuery
。我如何导出这些内容?
在 Webpack 5 中,我将使用 expose-loader
来实现此目的:
module.exports = {
module: {
rules: [
{
test: require.resolve('jquery'),
loader: 'expose-loader',
options: {exposes: ["$", "jQuery"]},
},
],
},
};
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: ["quot;, "jQuery"]},
},
],
},
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了让它与 esbuild 一起工作,您必须从模块导入一个对象,并在
window
上设置该对象。例如,jQuery 将
jQuery
对象导出为默认值。要将其导出为全局,您必须执行以下操作: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.,jQuery exports the
jQuery
object as the default value. To export it as a global you have to do: