0

I have a JS config file exported as an CJS module that I would like to parse and do something with whenever a change is detected. I have the watcher set up and it ends up calling this function:

const parseConfig = async (path: string) => {
  let config;

  try {
    config = (await import(path)).default;
  } catch (_) {
    // something went wrong, maybe it was malformed
  }

  return config;
};

As you can see I'm using a dynamic import to retrieve the JS file. This works, except for the fact that after it's imported the first time it appears to get cached, and doesn't update after that.

Is there a way to discard the existing import and force a re-import of a dynamically imported JS file?

Alternatively, if there is a more straightforward solution for this I'm open to suggestions.

NB: I'm using esbuild so it's resolving my import statements for me; I tried switching it to a dynamic require statement since it's CJS, but it had the same effect.

Jody Heavener
  • 2,704
  • 5
  • 41
  • 70

0 Answers0