From 51e5b74a7c9f340ad2d56d816bad1897b409ee7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=87=8E=E5=A3=B0?= Date: Tue, 5 Sep 2023 20:05:53 +0800 Subject: [PATCH] feat(builder): watch mode add debounce --- libs/cfworker-builder/lib/gen-toml.mjs | 10 ++++++++-- libs/cfworker-builder/lib/utils/debounce.mjs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 libs/cfworker-builder/lib/utils/debounce.mjs diff --git a/libs/cfworker-builder/lib/gen-toml.mjs b/libs/cfworker-builder/lib/gen-toml.mjs index e0981977..105871d3 100644 --- a/libs/cfworker-builder/lib/gen-toml.mjs +++ b/libs/cfworker-builder/lib/gen-toml.mjs @@ -4,6 +4,8 @@ import { readFileSync, writeFileSync, watch as _watch } from 'fs'; import MagicString from 'magic-string'; +import { debounce } from './utils/debounce.mjs'; + const tplFilePath = './wrangler.tpl.toml'; const targetFilePath = './wrangler.toml'; @@ -34,11 +36,15 @@ export function run() { writeFileSync(targetFilePath, magic.toString()); } +const debouncedRun = debounce(run, 300); + export function watch() { console.log('watching template file changes...'); _watch(tplFilePath, {}, () => { - console.log(`${tplFilePath} changed.`); - run(); + console.log( + `- ${new Date().toLocaleString('zh-CN')}: ${tplFilePath} changed.`, + ); + debouncedRun(); }); } diff --git a/libs/cfworker-builder/lib/utils/debounce.mjs b/libs/cfworker-builder/lib/utils/debounce.mjs new file mode 100644 index 00000000..c875090e --- /dev/null +++ b/libs/cfworker-builder/lib/utils/debounce.mjs @@ -0,0 +1,12 @@ +export function debounce(func, wait) { + let timer = null; + return (...args) => { + if (timer) { + clearTimeout(timer); + } + + timer = setTimeout(() => { + func.apply(this, args); + }, wait); + }; +}