esbuild Guide

Learn esbuild in Simple English

What Is esbuild?

esbuild is a fast JavaScript and CSS build tool. It can bundle source files, transform modern JavaScript and TypeScript syntax, minify code, generate source maps, and prepare applications for production.

It is designed with speed in mind and is commonly used as part of modern frontend development workflows.

Simple idea: esbuild takes your source code and can transform, bundle, and optimize it into output files for browsers or other JavaScript environments.

Official website: esbuild documentation.

Why Was esbuild Created?

Large JavaScript projects can contain hundreds or thousands of files. Processing all those files individually may be inefficient for some applications.

A build tool can combine modules, transform syntax, optimize output, and help prepare an application for deployment.

esbuild focuses heavily on making these operations fast.

What Can esbuild Do?

What Do You Need Before Learning esbuild?

Before using esbuild, it helps to understand:

You do not need to master every advanced JavaScript feature before learning the basics of a build tool.

Installing esbuild

For a typical Node.js project, install esbuild with npm as a development dependency:

npm install --save-dev esbuild

You can run the locally installed version using npx:

npx esbuild --version

This displays the installed esbuild version when installation has completed successfully.

Build tools are commonly installed as development dependencies because they are used to create application files rather than being needed directly by the application at runtime.

Creating a Simple Project

Create a project folder and enter it:

mkdir esbuild-project
cd esbuild-project

Create a package.json file:

npm init -y

Install esbuild:

npm install --save-dev esbuild

Create a source folder:

mkdir src

Your project will now have a place for source code and its npm configuration.

Your First JavaScript File

Create a file named src/index.js and add this code:

const message = "Hello from esbuild!";

console.log(message);

This is ordinary JavaScript. esbuild can transform or bundle it when you run a build command.

Your First esbuild Build

First, create the output directory:

mkdir dist

Then run:

npx esbuild src/index.js --bundle --outfile=dist/app.js

This command tells esbuild to:

esbuild does not automatically create a missing parent output directory in every situation. Create dist first, or use an appropriate directory-creation command for your operating system.

Understanding Entry Points

An entry point is the main file from which esbuild starts building your application.

For example:

src/index.js

If this file imports other local files, esbuild can follow those imports during bundling.

import { add } from "./math.js";

console.log(add(5, 3));

The file math.js must exist at the specified path and export the function being imported.

Working with Multiple JavaScript Files

Suppose your project contains:

src/
├── index.js
├── math.js
└── message.js

The math.js file:

export function add(a, b) {
    return a + b;
}

The message.js file:

export const message = "Welcome to TechLearn Hub!";

The main index.js file:

import { add } from "./math.js";
import { message } from "./message.js";

console.log(message);
console.log(add(10, 20));

Build the main file:

npx esbuild src/index.js --bundle --outfile=dist/app.js

esbuild follows the imports and combines the required code into the generated output.

What Is Bundling?

Bundling means combining modules and their dependencies into one or more output files.

A project may contain many separate files, such as:

index.js
math.js
user.js
api.js
utils.js

Instead of manually combining them, a bundler analyzes their relationships and generates the appropriate output.

Bundling can simplify deployment and reduce the number of JavaScript files a browser needs to request. The best setup depends on the application.

Minification

Minification removes unnecessary characters from code while preserving its intended behavior. It may shorten variable names and remove extra whitespace.

Example:

npx esbuild src/index.js --bundle --minify --outfile=dist/app.js

The generated output can be smaller than readable development code.

Keep your original source files. Minified output is harder for humans to read and is generally intended for distribution rather than everyday editing.

Source Maps

Bundled or minified code can be difficult to debug. Source maps help browser and developer tools connect generated code to the original source files.

npx esbuild src/index.js --bundle --sourcemap --outfile=dist/app.js

This produces the bundled JavaScript and a source map alongside it.

Source maps are useful during development. Before publishing them, consider whether exposing original source details is appropriate for your project.

Development and Production Builds

During development, you may want source maps and output that is easier to inspect.

Development build

npx esbuild src/index.js --bundle --sourcemap --outfile=dist/app.js

Production build

npx esbuild src/index.js --bundle --minify --outfile=dist/app.js

The production command minifies the bundled output. A real application may also require environment settings, asset handling, tests, and other build steps.

TypeScript Support

esbuild can transform TypeScript files into JavaScript.

Create src/index.ts:

const name: string = "TechLearn Hub";

console.log(name);

Build it with:

npx esbuild src/index.ts --outfile=dist/app.js
esbuild transforms TypeScript syntax but does not perform complete TypeScript type checking. For type checking, install TypeScript and run the compiler separately.

For example:

npm install --save-dev typescript
npx tsc --noEmit

A TypeScript project may need a suitable tsconfig.json file for its type-checking settings.

JSX Support

JSX is a syntax often used with React. esbuild can transform JSX into JavaScript.

function App() {
    return <h1>Hello World</h1>;
}

export default App;

Save JSX code in a file such as src/App.jsx. A basic transformation can be run with:

npx esbuild src/App.jsx --loader:.jsx=jsx --outfile=dist/App.js

For a full React application, you may also need React packages, the appropriate JSX runtime configuration, and a development or serving setup.

CSS Support

esbuild can process CSS as well as JavaScript.

Create src/style.css:

body {
    font-family: Arial, sans-serif;
    margin: 0;
}

h1 {
    color: blue;
}

Build the CSS:

npx esbuild src/style.css --outfile=dist/style.css

You can also use CSS imports from JavaScript in a bundled workflow. Check the generated output and your application setup to make sure the stylesheet is loaded correctly.

CSS Minification

CSS can be minified to reduce the size of the stylesheet.

npx esbuild src/style.css --minify --outfile=dist/style.css

Smaller files can reduce the amount of data users need to download, although actual performance also depends on caching, network conditions, and the rest of the page.

Watch Mode

Watch mode allows esbuild to rebuild when relevant source files change.

npx esbuild src/index.js --bundle --outfile=dist/app.js --watch

This is useful during development when you repeatedly edit your source code.

Watch mode rebuilds files; it does not automatically provide a complete development server or hot module replacement system.

Using an esbuild Configuration

For simple projects, command-line options may be enough. For larger projects, the JavaScript API can help organize the build configuration.

Create a file named build.cjs:

const esbuild = require("esbuild");

esbuild.build({
    entryPoints: ["src/index.js"],
    bundle: true,
    outfile: "dist/app.js"
}).catch(() => process.exit(1));

Make sure the dist directory exists before running the script. Then run:

node build.cjs

Using the JavaScript API

esbuild provides an API that allows JavaScript or Node.js programs to control the build process.

const esbuild = require("esbuild");

async function build() {
    await esbuild.build({
        entryPoints: ["src/index.js"],
        bundle: true,
        minify: true,
        sourcemap: true,
        outfile: "dist/app.js"
    });
}

build().catch((error) => {
    console.error(error);
    process.exit(1);
});

This example uses CommonJS syntax. If your project uses ES modules, configure the file and imports accordingly.

External Dependencies

Sometimes a dependency should not be included inside the generated bundle. You can mark packages or modules as external.

npx esbuild src/index.js --bundle --external:some-package --outfile=dist/app.js

Replace some-package with the actual package name. The external dependency must be available to the environment where the output runs.

Targeting Older Browsers

Modern JavaScript syntax may not work in every browser. You can specify a target environment for syntax transformation.

npx esbuild src/index.js --bundle --target=es2018 --outfile=dist/app.js

Choose a target based on the browsers and JavaScript environments your application supports. A target does not automatically provide every missing browser API or polyfill.

Output Formats

Different applications may need different JavaScript module formats.

For example, you can choose an output format with:

npx esbuild src/index.js --bundle --format=esm --outfile=dist/app.js

The appropriate format depends on where and how the generated code will run.

Code Splitting

Large applications do not always need to load every part of their JavaScript at once.

Code splitting allows an application to generate multiple output chunks when the module structure and build settings support it.

For esbuild, code splitting is designed for ESM output. A basic example is:

npx esbuild src/index.js --bundle --splitting --format=esm --outdir=dist

This requires suitable entry points or dynamic imports for splitting to be useful. The resulting files must be deployed together so that their imports can be resolved.

Dynamic Imports

JavaScript supports dynamic imports for loading modules when needed.

async function loadFeature() {
    const feature = await import("./feature.js");
    feature.start();
}

loadFeature();

The feature.js file must exist and export a compatible start function. Dynamic imports can help defer loading features that are not needed immediately.

Plugins

Plugins allow developers to extend esbuild's build behavior through its JavaScript API.

Plugins can help with specialized tasks such as:

Plugin capabilities depend on the plugin implementation and the esbuild API hooks it uses.

Example Plugin Concept

The following simplified example shows how a plugin can intercept a custom import path:

const plugin = {
    name: "example-plugin",

    setup(build) {
        build.onResolve(
            { filter: /^example:/ },
            (args) => {
                return {
                    path: args.path,
                    external: true
                };
            }
        );
    }
};

This example marks matching imports as external. A complete plugin may also need loading logic, validation, and error handling.

esbuild and React

esbuild can transform JSX and can therefore be part of React-related build workflows.

A complete React application usually needs more than a bundler. Depending on the project, you may also need:

Some frameworks and development tools provide these features as part of a larger workflow.

esbuild and Node.js

esbuild can also bundle source code for Node.js applications.

npx esbuild src/server.js --bundle --platform=node --outfile=dist/server.js

Node.js applications may need certain dependencies to remain external, depending on native modules, runtime behavior, and the deployment environment.

Browser Builds

For browser applications, you can configure esbuild for the browser platform.

npx esbuild src/index.js --bundle --platform=browser --outfile=dist/app.js

The generated JavaScript must be included in an HTML page or another appropriate browser entry point.

Package Scripts

Instead of typing long commands every time, you can add a build script to package.json.

{
  "scripts": {
    "build": "esbuild src/index.js --bundle --minify --outfile=dist/app.js"
  }
}

Before running the script, make sure the dist folder exists. Then run:

npm run build

You can create the directory manually or use a cross-platform directory-creation tool in your build workflow.

A Simple Project Structure

esbuild-project/
├── src/
│   ├── index.js
│   ├── math.js
│   └── message.js
├── dist/
├── package.json
├── package-lock.json
└── node_modules/

The src folder contains source code, while dist can contain generated files intended for testing or deployment.

esbuild vs Webpack

Feature esbuild Webpack
Main focus Fast builds and transformations Highly configurable application bundling
Configuration Often simple for basic projects Can become extensive
Plugins Supported through the API Extensive plugin ecosystem
JavaScript Supported Supported
TypeScript Transforms TypeScript syntax Often configured through loaders and other tools

The tools overlap, but they have different design goals and ecosystems. The right choice depends on the project's requirements.

esbuild vs Rollup

Feature esbuild Rollup
Design focus Fast bundling and transformation Module bundling with strong tree-shaking workflows
Plugins Supported Extensive plugin ecosystem
Libraries Can build libraries Popular for library builds
Configuration Can be concise Flexible and customizable

Both tools can be useful. Consider your output formats, plugins, and deployment needs when choosing between them.

esbuild vs Vite

esbuild and Vite are not exactly the same kind of tool.

Vite is a broader frontend development tool that provides a development server, a fast development workflow, production build capabilities, and framework integrations.

esbuild is primarily a fast build and transformation tool. Vite can use esbuild for certain transformations while using other tooling for additional parts of its workflow.

Modern frontend projects often use several technologies together rather than relying on one tool for every task.

Advantages of esbuild

Limitations to Understand

Common Beginner Mistakes

  1. Forgetting to install esbuild.
  2. Using the wrong entry-point path.
  3. Not creating the output directory.
  4. Expecting bundling to replace TypeScript type checking.
  5. Using production settings without understanding them.
  6. Ignoring browser compatibility requirements.
  7. Marking a dependency as external without making it available at runtime.
  8. Assuming watch mode is the same as a development server.
  9. Deploying only one generated file when other chunks or assets are required.

Beginner Example Project

Imagine this project:

my-app/
├── src/
│   ├── index.js
│   └── math.js
└── package.json

math.js

export function multiply(a, b) {
    return a * b;
}

index.js

import { multiply } from "./math.js";

const result = multiply(5, 4);

console.log(result);

Install esbuild, then create the output directory:

npm install --save-dev esbuild
mkdir dist

Build the application:

npx esbuild src/index.js --bundle --minify --outfile=dist/app.js

The generated dist/app.js file contains the bundled JavaScript. In this example, running it in a suitable JavaScript environment prints the result, 20.

Useful esbuild Commands

# Install esbuild
npm install --save-dev esbuild

# Check the installed version
npx esbuild --version

# Create an output directory
mkdir dist

# Transform a JavaScript file
npx esbuild src/index.js --outfile=dist/app.js

# Bundle JavaScript
npx esbuild src/index.js --bundle --outfile=dist/app.js

# Bundle and minify
npx esbuild src/index.js --bundle --minify --outfile=dist/app.js

# Generate a source map
npx esbuild src/index.js --bundle --sourcemap --outfile=dist/app.js

# Watch for source changes
npx esbuild src/index.js --bundle --watch --outfile=dist/app.js

# Run the package build script
npm run build
The lines beginning with # are comments for Unix-style shells. If you run commands one by one in a terminal that does not support this comment syntax, enter only the command you need.

How esbuild Fits Into a Modern Workflow

  1. Write source code.
  2. Install project dependencies.
  3. Configure the build.
  4. Create the output directory.
  5. Run esbuild.
  6. Transform source files.
  7. Bundle modules when needed.
  8. Minify production files when appropriate.
  9. Generate source maps when useful.
  10. Test the generated application.
  11. Deploy all required output files.

When Should You Learn esbuild?

esbuild is useful if you want to understand how modern JavaScript build systems work.

It is especially useful for learning about:

Learning Roadmap

  1. Learn JavaScript basics.
  2. Learn JavaScript modules.
  3. Learn npm and package.json.
  4. Install esbuild.
  5. Create a basic build.
  6. Understand entry points and output files.
  7. Learn bundling and minification.
  8. Learn source maps.
  9. Practice TypeScript builds.
  10. Practice JSX builds.
  11. Explore the JavaScript API.
  12. Learn how plugins work.
  13. Use esbuild in a small real project.

Quick Cheat Sheet

Task Command or Concept
Install npm install --save-dev esbuild
Check version npx esbuild --version
Bundle --bundle
Minify --minify
Source map --sourcemap
Watch --watch
Browser platform --platform=browser
Node platform --platform=node
Target --target=es2018
External package --external:some-package
Output directory --outdir=dist

Frequently Asked Questions

Is esbuild a programming language?

No. esbuild is a build tool for processing JavaScript, TypeScript, CSS, and related source code.

Is esbuild a JavaScript framework?

No. It is a build tool, not a frontend framework.

Can esbuild bundle JavaScript?

Yes. Bundling JavaScript is one of its important capabilities.

Can esbuild process TypeScript?

Yes. It transforms TypeScript syntax, but complete type checking requires a separate tool such as the TypeScript compiler.

Does esbuild support JSX?

Yes. It can transform JSX and TSX syntax.

Can esbuild minify code?

Yes. It can minify JavaScript and CSS.

Can esbuild generate source maps?

Yes. Source map generation is supported.

Does esbuild create the dist directory automatically?

You should create the output directory before building if it does not already exist. For example, create dist before using --outfile=dist/app.js.

Does esbuild include a development server?

esbuild has a watch mode and a basic development server API, but it does not provide the same complete frontend development workflow as tools such as Vite.

Is esbuild useful for beginners?

Yes. It can help beginners understand build systems, especially after learning JavaScript modules and npm.

Conclusion

esbuild is a fast build tool for JavaScript, TypeScript, JSX, CSS, and related web development workflows.

It can bundle files, transform source code, minify output, generate source maps, watch files, and provide programmable build APIs.

Understanding esbuild helps you learn an important part of modern web development: how source code is transformed into files ready for testing and deployment.

Next step: Explore how Vite, Rollup, and Webpack fit into the larger frontend build ecosystem.

Continue learning from the JavaScript Guide and the Web Development Guide.