更新
用户@TKoL 建议在窗口对象中定义一个属性。这产生了我想要达到的结果,尽管我不知道这是否是正确的方法。我将暂时使用这种方法。谢谢!
我正在使用 esbuild在我的项目中(第一次使用 bundler/以这种“风格”开发 JS)。
该项目是一个小型 Web 组件,我为此开发了一个最终用户应该能够在其脚本中使用的类。
// this is the component, which is then bundled and minified by esbuild.
// i have omitted various imports required in the class here.
export default class Widget extends HTMLElement {
/// code here is not relevant
}
customElements.define('custom-widget', Widget);
就目前而言,最终用户能够像这样使用 HTML 中的小部件:<custom-widget some-custom-attribute="some-value"></custom-widget>
let widget = document.querySelector('custom-widget');
widget.someMethodDefinedInTheClass();
但是,我希望用户也可以通过 JavaScript 完成所有操作。如何制作 esbuild 揭露小工具 类到全局范围?我想这样做以启用以下行为:
let wOptions = {}; // object of initialization options for the widget
let widget = new Widget(wOptions);
someContainer.append(widget);
widget.someMethodDefinedInTheClass();
最佳答案
要使任何方式 bundle 的 js 文件向全局范围公开任何内容,您必须将其设置为 global 的属性对象(表示全局范围),如
globalThis.Widget = Widget;
globalThis
关键字是在 javascript 中使用全局对象的最佳方式,因为它在浏览器页面、nodejs 或 service worker 环境中的工作方式相同。如果您的代码只在浏览器页面上执行,您也可以使用 window
关键词。
关于javascript - 如何使用 esbuild 将类公开到全局范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64806255/