5

My main code is under chokidar watched folder, when a file changes it emit an event

The main script is this

const fileName = "test.ts";
import(fileName).then((t: any) => {
  t.default();
});

and this is the file test.ts

export default () => {
  console.log("aaa");
};

I need to reimport file when I change test.ts, for example, I need this

START script

OUTPUT "aaa"

CHANGE test.ts from "console.log("aaa")" to "console.log("bbb")"

OUTPUT "bbb"

Community
  • 1
  • 1
Mauro Sala
  • 1,166
  • 2
  • 12
  • 33
  • For me it was a better solution handling the invalidation myself as not only the imported file directly needed to me invalidated but also a subsequent import. So I found this more helpful: https://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate – Jonathan Dec 11 '19 at 14:33

1 Answers1

1

The solution is to use decache, full code is this (with chokidar folder watcher)

const folder = chokidar.watch("./myFolder", {
    ignored: /(^|[\/\\])\../,
    persistent: true,
});
folder
.on("add", (fileName: string) => {
    const mod = require(fileName)
    mod.default();
.on("change", (fileName: string) => {
    decache(fileName);
    const mod = require(fileName)
    mod.default();
})
Mauro Sala
  • 1,166
  • 2
  • 12
  • 33