简体   繁体   English

如何用esbuild将一个class暴露给全局scope?

[英]How to expose a class to the global scope with esbuild?

Update更新

user @TKoL suggested defining a property in the window object. This produces the result I wanted to achieve, although I do not know if it is the correct way to proceed.用户@TKoL 建议在 window object 中定义一个属性。这会产生我想要实现的结果,尽管我不知道这是否是正确的处理方式。 I will be using this method for the time being.我将暂时使用这种方法。 Thanks!谢谢!


I am using esbuild in my project (first time using a bundler / developing JS in this "style").我在我的项目中使用esbuild (第一次使用捆绑器/以这种“风格”开发 JS)。 The project is a small web component for which I developed a class that the end user should be able to utilize in their scripts.该项目是一个小型 web 组件,我为此开发了一个 class,最终用户应该能够在他们的脚本中使用它。

// 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);

As it stands, the end user is able to utilize the widget from HTML like this:就目前而言,最终用户能够像这样使用 HTML 中的小部件:

<custom-widget some-custom-attribute="some-value"></custom-widget>

let widget = document.querySelector('custom-widget');
widget.someMethodDefinedInTheClass();

However, I would like to allow the user to do it all via JavaScript as well.但是,我也想允许用户通过 JavaScript 完成所有操作。

How can I make esbuild expose the Widget class to the global scope?如何让esbuildWidget class 暴露给全局 scope? I'd like to do this to enable behaviours such as:我想这样做以启用以下行为:

let wOptions = {}; // object of initialization options for the widget
let widget = new Widget(wOptions);
someContainer.append(widget);
widget.someMethodDefinedInTheClass();

To make any way bundled js file to expose anything to the global scope you have to set it as a property of global object (that represents the global scope) like要以任何方式捆绑 js 文件以向全局 scope 公开任何内容,您必须将其设置为全局object(代表全局范围)的属性,例如

globalThis.Widget = Widget;

globalThis keyword is a best way to use global object in javascript because it works the same on browser page, nodejs or service worker environment. globalThis关键字是在 javascript 中使用全局 object 的最佳方式,因为它在浏览器页面、nodejs 或 service worker 环境中工作相同。 If your code will be only executed on browser page you can also use window keyword.如果您的代码只在浏览器页面上执行,您还可以使用window关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM