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.
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?
- Bundle JavaScript applications
- Bundle CSS
- Transform modern JavaScript syntax
- Transform TypeScript syntax
- Process JSX and TSX
- Minify JavaScript and CSS
- Generate source maps
- Watch files for changes
- Build for browsers
- Build for Node.js
- Support plugins through its JavaScript API
- Provide a command-line interface
- Provide a programmable JavaScript API
What Do You Need Before Learning esbuild?
Before using esbuild, it helps to understand:
- Basic JavaScript syntax
- JavaScript modules and import/export
- Files and folders
- Node.js and npm basics
- The difference between source files and generated files
Installing esbuild
For a typical Node.js project, install esbuild with npm as a development dependency:
npm install --save-dev esbuildYou can run the locally installed version using npx:
npx esbuild --versionThis displays the installed esbuild version when installation has completed successfully.
Creating a Simple Project
Create a project folder and enter it:
mkdir esbuild-project
cd esbuild-projectCreate a package.json file:
npm init -yInstall esbuild:
npm install --save-dev esbuildCreate a source folder:
mkdir srcYour 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 distThen run:
npx esbuild src/index.js --bundle --outfile=dist/app.jsThis command tells esbuild to:
- Read
src/index.js - Bundle its dependencies when applicable
- Write the generated JavaScript to
dist/app.js
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.jsIf 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.jsThe 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.jsesbuild 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.jsInstead of manually combining them, a bundler analyzes their relationships and generates the appropriate output.
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.jsThe generated output can be smaller than readable development code.
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.jsThis 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.jsProduction build
npx esbuild src/index.js --bundle --minify --outfile=dist/app.jsThe 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.jsFor example:
npm install --save-dev typescript
npx tsc --noEmitA 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.jsFor 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.cssYou 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.cssSmaller 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 --watchThis is useful during development when you repeatedly edit your source code.
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.cjsUsing 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.jsReplace 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.jsChoose 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.
- ESM: commonly used with modern JavaScript modules.
- CommonJS: used in many Node.js projects.
- IIFE: can wrap code in a function for certain browser-script use cases.
For example, you can choose an output format with:
npx esbuild src/index.js --bundle --format=esm --outfile=dist/app.jsThe 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=distThis 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:
- Custom module resolution
- Loading special file types
- Transforming custom content
- Interacting with external systems
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:
- React and React DOM
- A development server
- Hot module replacement
- Routing integrations
- Asset handling
- Environment configuration
- Production deployment settings
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.jsNode.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.jsThe 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 buildYou 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
- Fast build operations
- JavaScript support
- TypeScript syntax transformation
- JSX and TSX support
- CSS processing and minification
- Source map generation
- Command-line interface
- JavaScript API
- Plugin support
- Useful options for browser and Node.js builds
Limitations to Understand
- It is primarily a build tool, not a complete application framework.
- TypeScript transformation is not full type checking.
- Large application workflows may require additional tools.
- Some advanced requirements may need plugins or custom configuration.
- Targeting older syntax does not automatically add every missing browser API.
Common Beginner Mistakes
- Forgetting to install esbuild.
- Using the wrong entry-point path.
- Not creating the output directory.
- Expecting bundling to replace TypeScript type checking.
- Using production settings without understanding them.
- Ignoring browser compatibility requirements.
- Marking a dependency as external without making it available at runtime.
- Assuming watch mode is the same as a development server.
- 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.jsonmath.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 distBuild the application:
npx esbuild src/index.js --bundle --minify --outfile=dist/app.jsThe 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# 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
- Write source code.
- Install project dependencies.
- Configure the build.
- Create the output directory.
- Run esbuild.
- Transform source files.
- Bundle modules when needed.
- Minify production files when appropriate.
- Generate source maps when useful.
- Test the generated application.
- 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:
- Bundling
- JavaScript modules
- TypeScript transformation
- JSX
- Minification
- Source maps
- Build pipelines
- Frontend performance
Learning Roadmap
- Learn JavaScript basics.
- Learn JavaScript modules.
- Learn npm and package.json.
- Install esbuild.
- Create a basic build.
- Understand entry points and output files.
- Learn bundling and minification.
- Learn source maps.
- Practice TypeScript builds.
- Practice JSX builds.
- Explore the JavaScript API.
- Learn how plugins work.
- 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.
Continue learning from the JavaScript Guide and the Web Development Guide.