DEV Community

Alex Spinov
Alex Spinov

Posted on

esbuild Has a Free API That Compiles JavaScript 100x Faster Than Webpack

esbuild is the Go-powered JavaScript bundler that transformed the build tool landscape. Its API is minimal but incredibly powerful.

The Build API

import * as esbuild from "esbuild";

await esbuild.build({
  entryPoints: ["src/index.ts"],
  bundle: true,
  minify: true,
  sourcemap: true,
  splitting: true,
  format: "esm",
  target: ["es2020"],
  outdir: "dist",
  metafile: true, // Generate build analysis
});
Enter fullscreen mode Exit fullscreen mode

The Transform API: In-Memory Compilation

const result = await esbuild.transform(tsCode, {
  loader: "tsx",
  target: "es2020",
  jsx: "automatic",
  minify: true,
});

console.log(result.code); // Compiled JS
console.log(result.map);  // Source map
Enter fullscreen mode Exit fullscreen mode

No filesystem. No config files. Pure in-memory transformation.

Plugin API: Extend Everything

const httpPlugin = {
  name: "http-import",
  setup(build) {
    // Intercept HTTP imports
    build.onResolve({ filter: /^https?:\/\// }, (args) => ({
      path: args.path,
      namespace: "http-url",
    }));

    // Fetch and return content
    build.onLoad({ filter: /.*/, namespace: "http-url" }, async (args) => {
      const response = await fetch(args.path);
      const contents = await response.text();
      return { contents, loader: "js" };
    });
  },
};

await esbuild.build({
  entryPoints: ["app.js"],
  bundle: true,
  plugins: [httpPlugin],
});
Enter fullscreen mode Exit fullscreen mode

Watch Mode + Serve API

const ctx = await esbuild.context({
  entryPoints: ["src/index.tsx"],
  bundle: true,
  outdir: "dist",
});

// Dev server with live reload
await ctx.serve({ servedir: "dist", port: 3000 });

// Watch for changes
await ctx.watch();
console.log("Watching...");
Enter fullscreen mode Exit fullscreen mode

Metafile Analysis: Bundle Insights

const result = await esbuild.build({
  entryPoints: ["src/index.ts"],
  bundle: true,
  metafile: true,
  outfile: "dist/bundle.js",
});

// Analyze bundle
const text = await esbuild.analyzeMetafile(result.metafile);
console.log(text);
// dist/bundle.js  152.3kb
//   node_modules/react-dom/...  98.1kb (64.4%)
//   src/components/...          32.5kb (21.3%)
Enter fullscreen mode Exit fullscreen mode

CSS Bundling

await esbuild.build({
  entryPoints: ["src/styles/main.css"],
  bundle: true,
  minify: true,
  outfile: "dist/styles.css",
  loader: {
    ".png": "dataurl",
    ".svg": "text",
    ".woff2": "file",
  },
});
Enter fullscreen mode Exit fullscreen mode

Benchmarks

Tool Build Time (1000 modules)
esbuild 0.33s
Vite (esbuild) 0.5s
Rollup 12s
Webpack 5 22s

Building high-performance tools? My Apify scraping tools are built for speed.

Custom build pipeline? Email spinov001@gmail.com

Top comments (0)