From 68c2c3482878ad7e623b466a3b3c8769af4f97a1 Mon Sep 17 00:00:00 2001 From: zanminkian Date: Sun, 15 Dec 2024 14:27:47 +0000 Subject: [PATCH] refactor: optimize action --- eslint.config.js | 8 +------- packages/tscx/src/action.ts | 39 ++++++++++++++++++++++++------------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 646d7b9..f9ad423 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -6,12 +6,6 @@ export default new Builder() .enablePackagejson() .enableJavascript() .enableTypescript({ - omit: [ - "@fenge/no-restricted-loops", - "@typescript-eslint/no-floating-promises", - "es-x/no-top-level-await", - "unicorn/no-process-exit", - "no-console", - ], + omit: ["@fenge/no-restricted-loops", "no-console"], }) .toConfig(); diff --git a/packages/tscx/src/action.ts b/packages/tscx/src/action.ts index 8a8169a..4a162c2 100644 --- a/packages/tscx/src/action.ts +++ b/packages/tscx/src/action.ts @@ -17,17 +17,9 @@ export class Action { this.compiler = new Compiler(options); } - private setupWatcher() { - const include = this.compiler.getInclude() ?? []; - const watchFiles = - include.length <= 0 - ? [process.cwd()] - : include - .map((i) => path.resolve(process.cwd(), i)) - .concat(path.resolve(process.cwd(), this.options.project)); - + private watch(paths: string[]) { this.watcher = chokidar - .watch(watchFiles, { + .watch(paths, { ignored: [ "**/node_modules/**", "**/.git/**", @@ -41,6 +33,29 @@ export class Action { .on("ready", () => this.cb()); } + private setupWatcher() { + const include = this.compiler.getInclude() ?? []; + const watchFiles = + include.length <= 0 + ? [process.cwd()] + : include + .map((i) => path.resolve(process.cwd(), i)) + .concat(path.resolve(process.cwd(), this.options.project)); + + if (this.watcher) { + // If this method throw an error (I mean the promise rejected), the process will exit with non-zero code. + // See https://github.com/zanminkian/zanminkian.github.io/issues/54 + this.watcher.close().then( + () => this.watch(watchFiles), + (e) => { + throw new Error("Close watcher fail!", { cause: e }); + }, + ); + } else { + this.watch(watchFiles); + } + } + private cb(filepath?: string) { console.log("File changes detected", filepath); // user edit non-tsconfig files @@ -66,10 +81,6 @@ export class Action { ); return; } - this.watcher?.close().catch((e) => { - console.error("Close watcher fail!", e); - process.exit(1); - }); this.setupWatcher(); this.lastUpdateTsconfigTime = now; }