How to Optimize Bundles with esbuild
Use esbuild for fast JS/TS bundling: entry points, code splitting, external deps, CSS and defining production globals correctly.
On this page
Introduction
esbuild is fast enough to change how you think about builds: bundling a large project in tens of milliseconds makes rebuilds during development and minification in CI feel instant. Its speed comes from being written natively and parallelising, and its configuration is deliberately small. Using it well means understanding entry points and code splitting, declaring what is external so you do not bundle your dependencies into a server build, and defining production globals so development code is stripped.
Why esbuild Is Fast
esbuild is written in a compiled language and uses parallelism, and it avoids the plugin overhead of a JavaScript-based bundler for its core work. The result is bundling and minification an order of magnitude faster, which is enough to run in a development server’s request path and to make CI minification negligible.
The speed is not free of caveats: its plugin ecosystem and its CSS handling are less complete than older bundlers, and some transformations require plugins that reduce the speed advantage. For most applications it is fast enough that the convenience of a small configuration outweighs the missing features.
import { build } from 'esbuild';
await build({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: 'dist/index.js',
platform: 'node',
target: 'node20',
format: 'esm',
minify: process.env.NODE_ENV === 'production',
sourcemap: true,
});
// tens of ms for a large project; fast enough to run on save
Entry Points and Code Splitting
An entry point is where a bundle starts; esbuild follows imports from there. Multiple entry points produce multiple bundles, and shared code can be split out with splitting so a dependency used by several entries is emitted once instead of duplicated. Splitting requires the esm output format.
For a browser app, one entry is the app and splitting pulls shared chunks out of lazy routes. For a library, one entry per export surface keeps consumers picking only what they use, provided the output format supports tree shaking downstream. Choose entry points to match the consumption shape.
await build({
entryPoints: {
app: 'src/app.tsx',
admin: 'src/admin.tsx',
},
bundle: true,
splitting: true, // shared code emitted once (requires format: 'esm')
format: 'esm',
outdir: 'dist',
chunkNames: 'chunks/[name]-[hash]',
});
// a dependency used by both app and admin becomes one shared chunk
External Dependencies and Platforms
For a Node build, bundling dependencies is often wrong: native modules cannot be bundled, and bundling a large dependency tree hides the real dependency list. Mark dependencies external so they stay as imports resolved at runtime, and bundle only your own code. external: [‘*’] with a plugin, or a list of the packages not to bundle.
Platform and format decisions follow: platform node, format esm or cjs matching the consumer. A server build should not bundle node_modules; a browser build should bundle everything except a CDN-loaded external. Getting this right avoids both a bloated bundle and a broken native module.
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync('package.json', 'utf8'));
await build({
entryPoints: ['src/server.ts'],
bundle: true,
platform: 'node',
format: 'esm',
outfile: 'dist/server.js',
external: [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.peerDependencies ?? {})],
});
// deps stay external (resolved at runtime); only your code is bundled
Defining Production Globals
define replaces identifiers at build time, which is how you strip development code: define process.env.NODE_ENV as “production” and dead-branch elimination removes the development branches. This is the difference between a bundle that ships debug code and one that does not.
Define the values as strings exactly as they should appear in the code, and be careful with process.env access: esbuild does not emulate Node’s process.env, so only the exact expressions you define are replaced. Define each variable you rely on, and confirm the output no longer contains the development code.
await build({
entryPoints: ['src/app.tsx'],
bundle: true,
platform: 'browser',
outfile: 'dist/app.js',
define: {
'process.env.NODE_ENV': '"production"', // string literal, not a value
'__DEV__': 'false',
},
minify: true,
});
// if (process.env.NODE_ENV !== 'production') { ... } is now eliminated
CSS, Assets and Loaders
esbuild handles CSS imports and can bundle them into a stylesheet, and loaders let you import other file types as data, text, binary or file URLs. This lets a single build process handle the app’s CSS and small assets without a separate tool, at the cost of less CSS processing than a dedicated pipeline.
For heavy CSS needs such as PostCSS plugins or Sass, esbuild can run them through plugins, but the speed advantage shrinks. Decide based on how much CSS processing you need: esbuild’s built-in CSS is enough for plain CSS and CSS modules; post-processing is where a plugin enters.
await build({
entryPoints: ['src/index.tsx'],
bundle: true,
outdir: 'dist',
loader: {
'.png': 'file', // asset URLs
'.svg': 'dataurl', // inline as data URL
'.txt': 'text', // import as string
},
// CSS is bundled from imported .css files automatically
});
// output includes dist/index.js and dist/index.css
Watching and the Development Server
Because a full rebuild is so fast, esbuild can be used in a watch mode or its own dev server, rebuilding on change without the incremental machinery other bundlers need. The dev server supports live reload and proxy configuration, which is enough for many development setups.
For a more featureful dev experience, esbuild is often used as the transform and bundler underneath another tool such as Vite, which adds the dev server and HMR on top. Using esbuild directly is simplest; using it underneath a framework gives features at a small cost.
import { context } from 'esbuild';
const ctx = await context({
entryPoints: ['src/index.tsx'],
bundle: true,
outdir: 'dist',
sourcemap: true,
define: { 'process.env.NODE_ENV': '"development"' },
});
await ctx.watch(); // rebuild on change, fast enough without incremental cache
// ctx.serve({ servedir: 'public' }) for a basic dev server
Common Pitfalls and Conclusion
Do not bundle node_modules into a server build; mark dependencies external or native modules break. Do not forget splitting requires esm output. Do not define globals with values instead of string literals; the replacement is literal. Do not assume esbuild emulates process.env fully. And do not expect its CSS pipeline to match a dedicated post-processor without plugins.
esbuild optimises bundles by being fast enough to run everywhere. Declare entry points and use splitting for shared code, mark dependencies external for a server build, define production globals as string literals so development branches are eliminated, use loaders for assets and CSS, and use watch or its dev server for development. The result is a build that is fast to run and straightforward to configure.
Sources: esbuild: Build API, esbuild: Code splitting, esbuild: Define.
FAQ
- Should I bundle dependencies for a Node server build?
- Usually not. Mark them external so they are resolved at runtime, because native modules cannot be bundled and bundling hides the real dependency list. Bundle only your own code for a server; bundle everything (except CDN externals) for a browser build.
- How do I strip development code?
- Use define with string literals, such as define: { "process.env.NODE_ENV": "\"production\"" }, so dead-branch elimination removes the development paths. Define the exact expressions you rely on, because esbuild does not emulate Node's process.env fully.
Report a problem with this articleOpens a pre-filled issue on GitHub.