'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. 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"). 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.
// 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:
<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.
How can I make esbuild expose the Widget class to the global 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();
Solution 1:[1]
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
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. If your code will be only executed on browser page you can also use window
keyword.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mikhail Sereniti |