javascriptnode.jstypescriptchokidar

nodejs re-import file when it changes


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"


Solution

  • 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();
    })