esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

in a plug-in, hook into watch mode being stopped (.stop() being called)

Open ghost91- opened this issue 2 years ago • 1 comments

Hey there,

I am currently working on writing a copy plugin for esbuild (yeah, yet another one, the existing ones unfortunately don't cover my use cases...). I want to be able to properly watch files when using watch mode, and so far, almost everything works kind of nicely. I just encountered a small problem: I can't find a way to have the plugin react to watch mode being stopped (.stop() being called on the BuildResult). But this is needed to do cleanup, i.e. stop the chokidar file watcher. When running esbuild regularly, not doing the cleanup probably is not an issue, but in unit tests (with jest), if the cleanup is not done, the tests start interfering with each other because the chokidar watcher outlives the individual test cases.

It seems like there is no way to do this because stop is synchronous, but the cleanup of the chokidar file watcher needs to be asynchronous. But I thought, I'd ask anyways, so is there a way to do this? Other copy plugins that handle watching simply seem to ignore this problem (e.g. https://github.com/tinchoz49/esbuild-plugin-copy-watch).

If there is no way to do this, how would you handle this kind of thing instead?

ghost91- avatar Apr 22 '22 17:04 ghost91-

Yeah maybe we need an onStop hook in watch mode for plugins.

We can quickly implement one through plugin params:

function testPlugin({ onStop }) {
  return {
    name: 'test',
    setup() {
      onStop(() => console.log('cleanup'))
    }
  }
}

const onStopCallbacks = []
const onStop = (cb) => onStopCallbacks.push(cb)

esbuild.build({
  ...options,
  plugins: [testPlugin({ onStop })]
}).then(async build => {
  build.stop()
  for (const cb of onStopCallbacks) await cb();
})

hyrious avatar Apr 24 '22 09:04 hyrious