When you need to expose a class globally, for example in a web project built with esbuild, you can add the class to the global object, such as window (in a browser environment), making it available globally. Here are the specific steps and examples:
Step 1: Create a Class
First, define a class that will be exposed globally. For example, create a Person class.
javascript// src/Person.js export class Person { constructor(name, age) { this.name = name; this.age = age; } introduce() { return `My name is ${this.name} and I am ${this.age} years old.`; } }
Step 2: Create an Entry File
In the entry file, import the Person class and attach it to the global object window.
javascript// src/index.js import { Person } from './Person.js'; window.Person = Person;
This way, the Person class can be accessed globally via window.Person.
Step 3: Build the Project with esbuild
Next, use esbuild to build the project. You can run esbuild from the command line or integrate it into a build script.
bashesbuild src/index.js --bundle --outfile=dist/bundle.js
This command bundles src/index.js as the entry point, includes all dependencies, and outputs to dist/bundle.js.
Step 4: Reference the Built File in HTML
Finally, include the built JavaScript file in your HTML document.
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test Page</title> </head> <body> <script src="dist/bundle.js"></script> <script> const john = new Person('John', 30); console.log(john.introduce()); // Output: My name is John and I am 30 years old. </script> </body> </html>
Summary
By doing this, we use esbuild to bundle and expose the Person class to the global object, allowing it to be accessed anywhere via the global variable. This method is highly useful when developing libraries or for specific project builds. Please note that excessive use of global variables can make code difficult to maintain and understand, so use it cautiously.