### 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 }) =>
{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 = () =>