How to manage complex configuration of esbuild

When you get to the point in your esbuild journey when you want to start using plugins, you can be surprised that all those are not available from the CLI interface. The only way of using them is from the build script, and therefore you will have to move the whole build configuration there. The documentation mentions the build script can be either in JS or GO - in this article I'll cover only the JS side.

The starting point

As an example, I'll move the CLI build command from create-react-app article in this series:

"scripts": {
    ....
    "esbuild": "esbuild src/index.js --bundle --outfile=dist/main.js --loader:.html=text --loader:.js=jsx --loader:.svg=dataurl"
  }

and replace it by a build script. The example provided by the documentation:

require('esbuild').build({
  entryPoints: ['app.jsx'],
  bundle: true,
  outfile: 'out.js',
}).catch(() => process.exit(1))

let us start, but leaves few important things out.

Working configuration

The build script that builds our code is as follow

#! node

require("esbuild")
  .build({
    entryPoints: ["src/index.js"],
    bundle: true,
    outfile: "dist/main.js",
    loader: {
      ".js": "jsx",
      ".svg": "dataurl",
      ".html": "text",
    },
  })
  .catch(() => process.exit(1));

If you save it as build.js in the top-level directory, you can run:

$ chmod +x build.js

If you compare how both scripts work, you will see one difference:

% npm run esbuild

> [email protected] esbuild
> esbuild src/index.js --bundle --outfile=dist/main.js --loader:.html=text --loader:.js=jsx --loader:.svg=dataurl


  dist/main.js   903.0kb
  dist/main.css   1019b 

⚡ Done in 60ms
% ./build.js                            
%  (no output)

If you like the default logging level that is set for CLI build, you need to add:

require("esbuild")
  .build({
    logLevel: "info",
    ...
    // rest of the configuration

after this change, the build.js runs like:

% ./build.js 

  dist/main.js   903.0kb
  dist/main.css   1019b 

⚡ Done in 62ms

Links

Summary

In this article, we have seen how to move non-trivial esbuild command from CLI parameters to JS script. You can find the complete code - the app & the build script in this repo+branch

26