### Register an on-start callback in Go Source: https://esbuild.github.io/plugins Example of defining an on-start callback within an esbuild plugin setup function using Go. ```go package main import "fmt" import "github.com/evanw/esbuild/pkg/api" import "os" var examplePlugin = api.Plugin{ Name: "example", Setup: func(build api.PluginBuild) { build.OnStart(func() (api.OnStartResult, error) { fmt.Fprintf(os.Stderr, "build started\n") return api.OnStartResult{}, nil }) }, } func main() { } ``` -------------------------------- ### Register an on-start callback in JavaScript Source: https://esbuild.github.io/plugins Example of defining an on-start callback within an esbuild plugin setup function using JavaScript. ```javascript let examplePlugin = { name: 'example', setup(build) { build.onStart(() => { console.log('build started') }) }, } ``` -------------------------------- ### Install esbuild with default settings Source: https://esbuild.github.io/getting-started The default installation flow where the platform-specific binary is automatically selected and the install script optimizes the command. ```bash npm install esbuild ``` -------------------------------- ### Install esbuild with --ignore-scripts and --no-optional Source: https://esbuild.github.io/getting-started This combination results in a broken installation because the binary is neither installed by npm nor downloaded by the install script. ```bash npm install esbuild --ignore-scripts --no-optional ``` -------------------------------- ### Install React dependencies Source: https://esbuild.github.io/getting-started Install the necessary React packages before bundling. ```bash npm install react react-dom ``` -------------------------------- ### Data URL format examples Source: https://esbuild.github.io/content-types Examples of how data URLs look for binary and textual data. ```text data:image/png;base64,iVBORw0KGgo= ``` ```text data:image/svg+xml,%0A ``` -------------------------------- ### esbuild bundle output for composes example Source: https://esbuild.github.io/content-types Output of bundling the composes example with `esbuild app.js --bundle --outdir=dist --loader:.css=local-css`. Shows the imported string as a space-separated list of composed local names and the bundled CSS with renamed classes. ```JavaScript (() => { // style.css var submit = "anim_pulse style_button style_submit"; // app.js var div = document.createElement("div"); div.className = submit; document.body.appendChild(div); })(); ``` ```CSS /* anim.css */ @keyframes anim_pulse { from, to { opacity: 1; } 50% { opacity: 0.5; } } .anim_pulse { animation: 2s ease-in-out infinite anim_pulse; } /* style.css */ .style_button { display: inline-block; } .style_submit { font-weight: bold; } ``` -------------------------------- ### Implement an onLoad plugin in Go Source: https://esbuild.github.io/plugins This example demonstrates creating a plugin in Go that intercepts .txt files, reads their content, and converts them into a JSON array of words. ```go package main import "encoding/json" import "io/ioutil" import "os" import "strings" import "github.com/evanw/esbuild/pkg/api" var exampleOnLoadPlugin = api.Plugin{ Name: "example", Setup: func(build api.PluginBuild) { // Load ".txt" files and return an array of words build.OnLoad(api.OnLoadOptions{Filter: `\.txt$`}, func(args api.OnLoadArgs) (api.OnLoadResult, error) { text, err := ioutil.ReadFile(args.Path) if err != nil { return api.OnLoadResult{}, err } bytes, err := json.Marshal(strings.Fields(string(text))) if err != nil { return api.OnLoadResult{}, err } contents := string(bytes) return api.OnLoadResult{ Contents: &contents, Loader: api.LoaderJSON, }, nil }) }, } func main() { result := api.Build(api.BuildOptions{ EntryPoints: []string{"app.js"}, Bundle: true, Outfile: "out.js", Plugins: []api.Plugin{exampleOnLoadPlugin}, Write: true, }) if len(result.Errors) > 0 { os.Exit(1) } } ``` -------------------------------- ### Verify esbuild installation on Windows Source: https://esbuild.github.io/getting-started Run the esbuild executable from the local node_modules folder to verify the installation on Windows systems. ```bash .\node_modules\.bin\esbuild --version ``` -------------------------------- ### Install esbuild via npm Source: https://esbuild.github.io/getting-started Download and install the esbuild command locally as a development dependency. ```bash npm install --save-exact --save-dev esbuild ``` -------------------------------- ### @import order example: entry.css, foreground.css, background.css, reset.css Source: https://esbuild.github.io/content-types Shows how CSS @import behaves differently from JavaScript import. The example includes entry.css importing foreground and background, which each import reset.css, leading to reset.css being evaluated multiple times. ```CSS @import "foreground.css"; @import "background.css"; ``` ```CSS @import "reset.css"; body { color: white; } ``` ```CSS @import "reset.css"; body { background: black; } ``` ```CSS body { color: black; background: white; } ``` -------------------------------- ### Importing a Base64 string Source: https://esbuild.github.io/content-types Example of how to import a file as a Base64 string using the base64 loader. ```javascript import base64string from './example.data' console.log(base64string) ``` -------------------------------- ### Importing a data URL Source: https://esbuild.github.io/content-types Example of how to import a file as a data URL using the dataurl loader. ```javascript import url from './example.png' let image = new Image image.src = url document.body.appendChild(image) ``` -------------------------------- ### Install esbuild with --no-optional Source: https://esbuild.github.io/getting-started Prevents npm from installing the platform-specific binary, forcing the install script to attempt a manual download which may be less robust in complex network environments. ```bash npm install esbuild --no-optional ``` -------------------------------- ### Verify esbuild installation on Unix Source: https://esbuild.github.io/getting-started Run the esbuild executable from the local node_modules folder to verify the installation on Unix systems. ```bash ./node_modules/.bin/esbuild --version ``` -------------------------------- ### Example file resolution paths Source: https://esbuild.github.io/plugins A list of potential file locations checked by node's package resolution algorithm when importing 'pkg/file' from 'src/entry.css'. ```text src/node_modules/pkg/file src/node_modules/pkg/file.css src/node_modules/pkg/file/package.json src/node_modules/pkg/file/main src/node_modules/pkg/file/main.css src/node_modules/pkg/file/main/index.css src/node_modules/pkg/file/index.css node_modules/pkg/file node_modules/pkg/file.css node_modules/pkg/file/package.json node_modules/pkg/file/main node_modules/pkg/file/main.css node_modules/pkg/file/main/index.css node_modules/pkg/file/index.css ``` -------------------------------- ### Install esbuild-wasm package Source: https://esbuild.github.io/getting-started Install the WebAssembly version of esbuild, which is slower than the native version and intended primarily for browser use or unsupported platforms. ```bash npm install --save-exact esbuild-wasm ``` -------------------------------- ### JSX source code example Source: https://esbuild.github.io/content-types An example of JSX syntax before it is converted into JavaScript. ```jsx import Button from './button' let button = render(button) ``` -------------------------------- ### Implement an onLoad plugin to process .txt files Source: https://esbuild.github.io/plugins This example demonstrates creating a plugin that intercepts .txt files, reads their content, and converts them into a JSON array of words. ```javascript import * as esbuild from 'esbuild' import fs from 'node:fs' let exampleOnLoadPlugin = { name: 'example', setup(build) { // Load ".txt" files and return an array of words build.onLoad({ filter: /\.txt$/ }, async (args) => { let text = await fs.promises.readFile(args.path, 'utf8') return { contents: JSON.stringify(text.split(/\s+/)), loader: 'json', } }) }, } await esbuild.build({ entryPoints: ['app.js'], bundle: true, outfile: 'out.js', plugins: [exampleOnLoadPlugin], }) ``` -------------------------------- ### WebAssembly Import Workflow Source: https://esbuild.github.io/plugins Example usage of importing a .wasm file in JavaScript. ```javascript import load from './example.wasm' load(imports).then(exports => { ... }) ``` -------------------------------- ### Using CSS Modules Source: https://esbuild.github.io/content-types Example of importing a CSS module into JavaScript and the corresponding CSS module file. ```javascript // app.js import { outerShell } from './app.module.css' const div = document.createElement('div') div.className = outerShell document.body.appendChild(div) ``` ```css /* app.module.css */ .outerShell { position: absolute; inset: 0; } ``` -------------------------------- ### Output of copy loader bundling Source: https://esbuild.github.io/content-types Example of the resulting out/app.js file after bundling with the copy loader, showing the rewritten import path with a content hash and preserved import assertion. ```javascript // app.js import json from "./example-PVCBWCM4.json" assert { type: "json" }; console.log(json); ``` -------------------------------- ### Importing CSS from JavaScript Source: https://esbuild.github.io/content-types Example of importing a CSS file directly into a JavaScript file for bundling. ```javascript import './button.css' export let Button = ({ text }) =>
{text}
``` -------------------------------- ### Implement onResolve Plugin Callback in Go Source: https://esbuild.github.io/plugins Example of using onResolve in Go to redirect local image paths and mark remote URLs as external. ```go package main import "os" import "path/filepath" import "github.com/evanw/esbuild/pkg/api" var exampleOnResolvePlugin = api.Plugin{ Name: "example", Setup: func(build api.PluginBuild) { // Redirect all paths starting with "images/" to "./public/images/" build.OnResolve(api.OnResolveOptions{Filter: `^images/`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { return api.OnResolveResult{ Path: filepath.Join(args.ResolveDir, "public", args.Path), }, nil }) // Mark all paths starting with "http://" or "https://" as external build.OnResolve(api.OnResolveOptions{Filter: `^https?://`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { return api.OnResolveResult{ Path: args.Path, External: true, }, nil }) }, } func main() { result := api.Build(api.BuildOptions{ EntryPoints: []string{"app.js"}, Bundle: true, Outfile: "out.js", Plugins: []api.Plugin{exampleOnResolvePlugin}, Write: true, Loader: map[string]api.Loader{ ".png": api.LoaderBinary, }, }) if len(result.Errors) > 0 { os.Exit(1) } } ``` -------------------------------- ### Expanded @import order example Source: https://esbuild.github.io/content-types Shows the CSS that the browser sees after replacing each @import with the imported file, leading to reset.css appearing twice. This demonstrates why the body ends up entirely black. ```CSS /* reset.css */ body { color: black; background: white; } /* foreground.css */ body { color: white; } /* reset.css */ body { color: black; background: white; } /* background.css */ body { background: black; } ``` -------------------------------- ### Sample Svelte component with reactive bindings Source: https://esbuild.github.io/plugins Example .svelte file content showing two number inputs bound to variables a and b, and a paragraph displaying their sum. This is the input that the plugin compiles. ```svelte

{a} + {b} = {a + b}

``` -------------------------------- ### Simple env plugin in Go Source: https://esbuild.github.io/plugins Defines an esbuild plugin named 'env' in Go that intercepts import paths matching ^env$ and loads them as JSON containing the current environment variables. The setup function registers OnResolve and OnLoad callbacks. Use this plugin by passing it in the Plugins array to api.Build. ```go package main import "encoding/json" import "os" import "strings" import "github.com/evanw/esbuild/pkg/api" var envPlugin = api.Plugin{ Name: "env", Setup: func(build api.PluginBuild) { // Intercept import paths called "env" so esbuild doesn't attempt // to map them to a file system location. Tag them with the "env-ns" // namespace to reserve them for this plugin. build.OnResolve(api.OnResolveOptions{Filter: `^env$`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { return api.OnResolveResult{ Path: args.Path, Namespace: "env-ns", }, nil }) // Load paths tagged with the "env-ns" namespace and behave as if // they point to a JSON file containing the environment variables. build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: "env-ns"}, func(args api.OnLoadArgs) (api.OnLoadResult, error) { mappings := make(map[string]string) for _, item := range os.Environ() { if equals := strings.IndexByte(item, '='); equals != -1 { mappings[item[:equals]] = item[equals+1:] } } bytes, err := json.Marshal(mappings) if err != nil { return api.OnLoadResult{}, err } contents := string(bytes) return api.OnLoadResult{ Contents: &contents, Loader: api.LoaderJSON, }, nil }) }, } func main() { result := api.Build(api.BuildOptions{ EntryPoints: []string{"app.js"}, Bundle: true, Outfile: "out.js", Plugins: []api.Plugin{envPlugin}, Write: true, }) if len(result.Errors) > 0 { os.Exit(1) } } ``` -------------------------------- ### Create app.jsx Source: https://esbuild.github.io/getting-started Create a file named app.jsx to serve as the entry point for the bundle. ```jsx import * as React from 'react' import * as Server from 'react-dom/server' let Greet = () =>

Hello, world!

console.log(Server.renderToString()) ``` -------------------------------- ### Bundling for the browser via CLI Source: https://esbuild.github.io/getting-started Use the esbuild CLI to bundle app.jsx with minification, source maps, and specific browser targets. ```bash esbuild app.jsx --bundle --minify --sourcemap --target=chrome58,firefox57,safari11,edge16 ``` -------------------------------- ### Bundle with esbuild CLI Source: https://esbuild.github.io/getting-started Run the esbuild command to bundle the application for Unix or Windows environments. ```bash ./node_modules/.bin/esbuild app.jsx --bundle --outfile=out.js ``` ```bash .\node_modules\.bin\esbuild app.jsx --bundle --outfile=out.js ``` -------------------------------- ### Build the esbuild executable Source: https://esbuild.github.io/getting-started Compile the esbuild binary from the source code using the Go compiler. ```bash go build ./cmd/esbuild ``` -------------------------------- ### Direct eval example Source: https://esbuild.github.io/content-types An example of direct eval where the evaluated code can access variables in the containing scope. ```javascript let y = 123; return eval('y') ``` -------------------------------- ### Example of default export problem: somelib.js Source: https://esbuild.github.io/content-types CommonJS module with __esModule marker and a default export. This is the module being imported in the example. ```javascript // somelib.js Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = 'foo'; ``` -------------------------------- ### Accessing build options in Go Source: https://esbuild.github.io/plugins This plugin accesses the initial build options to define process.env.NODE_ENV based on the minify settings. ```go package main import "github.com/evanw/esbuild/pkg/api" var examplePlugin = api.Plugin{ Name: "auto-node-env", Setup: func(build api.PluginBuild) { options := build.InitialOptions if options.Define == nil { options.Define = map[string]string{} } if options.MinifyWhitespace && options.MinifyIdentifiers && options.MinifySyntax { options.Define[`process.env.NODE_ENV`] = `"production"` } else { options.Define[`process.env.NODE_ENV`] = `"development"` } }, } func main() { } ``` -------------------------------- ### Install esbuild with --ignore-scripts Source: https://esbuild.github.io/getting-started Prevents the install script from running, causing the CLI to use a JavaScript shim instead of the optimized binary, which adds minor performance overhead. ```bash npm install esbuild --ignore-scripts ``` -------------------------------- ### composes directive example: app.js, style.css, anim.css Source: https://esbuild.github.io/content-types Shows how to use the CSS modules composes directive to reference other class selectors, including from other files with the from keyword. The example includes app.js importing a composed class, style.css composing button and pulse, and anim.css defining the pulse animation. ```JavaScript // app.js import { submit } from './style.css' const div = document.createElement('div') div.className = submit document.body.appendChild(div) ``` ```CSS /* style.css */ .button { composes: pulse from "anim.css"; display: inline-block; } .submit { composes: button; font-weight: bold; } ``` ```CSS /* anim.css */ @keyframes pulse { from, to { opacity: 1 } 50% { opacity: 0.5 } } .pulse { animation: 2s ease-in-out infinite pulse; } ``` -------------------------------- ### Configuring the dataurl loader via CLI Source: https://esbuild.github.io/content-types Configure the dataurl loader for the .png extension using the esbuild CLI. ```bash esbuild app.js --bundle --loader:.png=dataurl ``` -------------------------------- ### Verify bundle output Source: https://esbuild.github.io/getting-started Run the generated out.js file to verify the bundled output. ```bash

Hello, world!

``` -------------------------------- ### Configure file loader via CLI Source: https://esbuild.github.io/content-types Command-line configuration for the file loader, bundling app.js and copying .png files to the output directory. ```shell esbuild app.js --bundle --loader:.png=file --outdir=out ``` -------------------------------- ### Linking Generated CSS in HTML Source: https://esbuild.github.io/content-types Example of manually linking the generated CSS and JavaScript files in an HTML document. ```html ``` -------------------------------- ### Download esbuild binary for current platform Source: https://esbuild.github.io/getting-started Use this command on Unix systems to download the esbuild binary executable for your current platform to the current working directory. ```bash curl -fsSL https://esbuild.github.io/dl/v0.28.2 | sh ``` -------------------------------- ### Mixing Local and Global CSS Names Source: https://esbuild.github.io/content-types Examples of using :global and :local selectors to control CSS name scoping. ```css /* * This is a local name with the "local-css" loader * and a global name with the "global-css" loader */ .button { } /* This is a local name with both loaders */ :local(.button) { } /* This is a global name with both loaders */ :global(.button) { } /* "foo" is global and "bar" is local */ :global .foo :local .bar { } /* "foo" is global and "bar" is local */ :global { .foo { :local { .bar {} } } } ``` -------------------------------- ### Minification of newline escape sequences Source: https://esbuild.github.io/faq Example of a string literal containing newline escape sequences that is 21 bytes long. ```javascript var text="a\nb\nc\n"; ``` -------------------------------- ### Implement onResolve Plugin Callback Source: https://esbuild.github.io/plugins Example of using onResolve to redirect local image paths and mark remote URLs as external. ```javascript import * as esbuild from 'esbuild' import path from 'node:path' let exampleOnResolvePlugin = { name: 'example', setup(build) { // Redirect all paths starting with "images/" to "./public/images/" build.onResolve({ filter: /^images\// }, args => { return { path: path.join(args.resolveDir, 'public', args.path) } }) // Mark all paths starting with "http://" or "https://" as external build.onResolve({ filter: /^https?:\/\// }, args => { return { path: args.path, external: true } }) }, } await esbuild.build({ entryPoints: ['app.js'], bundle: true, outfile: 'out.js', plugins: [exampleOnResolvePlugin], loader: { '.png': 'binary' }, }) ``` -------------------------------- ### Minified template literal Source: https://esbuild.github.io/faq Example of an equivalent template literal that is 18 bytes long, demonstrating how esbuild optimizes byte count. ```javascript var text=`a b c `; ```