21 days ago

What is the method for synchronously releasing resources in rollup?

As a JavaScript developer using the rollup bundler, I am facing issues with closing the old server running on a specific port when the rollup.config.mjs file is reloaded. Even though I have a custom rollup plugin that uses the closeWatcher hook to free up the port, rollup does not wait for the closeWatcher handler to finish before attempting to re-execute the config file. As a result, the port is still in use, and the execution fails. I have provided a minimal reproduction on stackblitz, and I need help to force rollup to let me free up resources like the port before trying to re-execute the config file.
21 days ago
Verified Answer
You can use the makeHot hook in your custom Rollup plugin to delay the reloading of the config file until after your closeWatcher handler has finished executing. Here's an example implementation:
export default function myPlugin() {
  // Create the server and get the server object and port number

  function closeWatcher() {
    return new Promise((resolve) => {
      // Close the server and free up the port
      // Resolve the promise when the server is successfully closed
      server.close(() => {
        console.log('Server closed');

  return {
    name: 'my-plugin',
    buildStart() {
      // Make the Rollup watcher hot with HMR enabled
      return this.makeHot(); // This is what delays the reload until after closeWatcher has finished
In this implementation, the makeHot hook is called in the buildStart function of your plugin to make the Rollup watcher hot. This means that hot module replacement (HMR) is enabled, allowing Rollup to update the bundle in the browser without requiring a full page refresh. The addWatchFile method is used to watch both the rollup.config.js and server files. This ensures that Rollup waits for both files to be saved before reloading. The closeWatcher function is called when the rollup.config.js file is reloaded. This function closes the server and frees up the port that it was using. The resolve method is called once the server is closed, signaling to Rollup that the resource is free. Because makeHot is called in the buildStart hook, it will hold off on reloading the configuration until after the closeWatcher handler has finished executing. This ensures that the port is freed up before Rollup attempts to re-execute the config file.