How to configure esbuild with a build script

In this article, I will show how to use build scripts in esbuild. So far in this series, we've been using command-line (CLI) arguments to configure our builds. As our configuration is growing, it can become cumbersome. And what's even more important, some esbuild features - such as plugins - are not available from CLI.


I want to keep the npm scripts set up in the dev sever part. Plus, I still want to avoid code duplication.

Executable script

First, let's start by adding an executable file. The easiest way will be:

$ touch build.js
(no output)
$ chmod +x build.js
(no output)

To make the file executable with node, we have to start the file with:

#!/usr/bin/env node

We can add a simple console.log to see if it works as expected:


With all this in place, we can call it directly from the terminal:

$ ./build.js 

(thanks to BenVida for pointing it our in a comment to other article).

Basic build script

Now, we can make the build script work for our basic case npm run build. Let's set the build.js set:

#!/usr/bin/env node

    logLevel: "info",
    entryPoints: ["src/index.js"],
    bundle: true,
    outfile: "www/main.js",
  .catch(() => process.exit(1));

A longer discussion of the basic build is my older post.

npm scripts update

We can already use this script via npm run build, and we can update package.json:

  "scripts": {
    "build": "./build.js",

With this, our build works:

$ npm run build

> esbuild-tutorial@1.0.0 build /home/marcin/workspace/github/esbuild-tutorial
> ./build.js

  www/main.js   151b 
  www/main.css   44b 

⚡ Done in 2ms
tuxy [npm run build] ~/workspace/github/esbuild-tutorial                                                                                                                  8:09
tuxy% npm run watch

> esbuild-tutorial@1.0.0 watch /home/marcin/workspace/github/esbuild-tutorial

But unfortunately, the parameters we add for watch or start are ignored:

$ npm run build -- --watch

> esbuild-tutorial@1.0.0 build /home/marcin/workspace/github/esbuild-tutorial
> ./build.js "--watch"

  www/main.js   151b 
  www/main.css   44b 

⚡ Done in 2ms


Repo, branch.

You can check out my video course about esbuild.


In this article, we have started refactoring towards build script with esbuild. The current script works fine for our build script, and I will address the other two in next article in this series.