Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get esbuild to watch for changes, rebuild, and restart express server

I am trying to create a simple SSR powered project using express + react. To do this, I need to simultaneously watch frontend and backend scripts during development.

The goal here is to use express routes to point to react page components. Now, I have this working, but I am having problems with DX.

Here are my package scripts:

    "build:client": "esbuild src/index.js --bundle --outfile=public/bundle.js --loader:.js=jsx",
    "build:server": "esbuild src/server.jsx --bundle --outfile=public/server.js --platform=node",
    "build": "npm run build:client && npm run build:server",
    "start": "node ./public/server.js"

Now this works if I do npm run build && npm run start, but the problem is that it doesn't watch for changes and rebuild the frontend bundle or restart the backend server.

Now, if I add --watch to the 2 build scripts, it only starts watching the index.js file and does not execute the other scripts.

So if I add nodemon to my start script, it doesn't matter because esbuild won't get past the first script due to the watcher.

Is there a simpler way of doing what I am trying to do here? I also want to add tailwind to this project once I figure this out, so any tips around that would be helpful as well.

like image 410
jaxramus Avatar asked Dec 11 '25 10:12

jaxramus


1 Answers

I use this code snippet to watch my custom react and esbuild project

const esbuild = require("esbuild");
async function watch() {
  let ctx = await esbuild.context({
    entryPoints: ["./src/app.tsx"],
    minify: false,
    outfile: "./build/bundle.js",
    bundle: true,
    loader: { ".ts": "ts" },
  });
  await ctx.watch();
  console.log('Watching...');
}

// IMPORTANT: this call MUST NOT have an `await`.
watch();

// If the call above had an `await`, Node would return
// immediately and you would NOT have the watcher
// running. Alternative, you could use an iife[1]:
(async() => {
  // The same code from the `watch` function above.
  // Notice that it also doesn't have an `await` in
  // front of it.
})()

For more details: https://esbuild.github.io/api/#watch

[1] IIFE: Immediately Invoked Function Expression

like image 148
Zahin Afsar Avatar answered Dec 12 '25 23:12

Zahin Afsar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!