Skip to content

Commit 19f7b70

Browse files
committed
feat: debounce reBuild
1 parent 939105b commit 19f7b70

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

packages/vite/src/node/build.ts

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -979,27 +979,43 @@ async function buildEnvironment(
979979
}
980980
}
981981

982+
let debouncedBuild: NodeJS.Timeout | undefined
983+
984+
function debounceBuild() {
985+
cancelBuild()
986+
debouncedBuild = setTimeout(async () => {
987+
const startTime = Date.now()
988+
await build()
989+
logger.info(
990+
`${colors.green(`✓ rebuilt in ${displayTime(Date.now() - startTime)}`)}`,
991+
)
992+
}, 20)
993+
}
994+
995+
function cancelBuild() {
996+
if (debouncedBuild) clearTimeout(debouncedBuild)
997+
}
998+
982999
server.watcher.on('change', async (file) => {
9831000
// The playground/hmr test `plugin hmr remove custom events` need to skip the change of unused files.
9841001
if (!bundle!.watchFiles.includes(file)) {
9851002
return
9861003
}
9871004

988-
const startTime = Date.now()
9891005
const hmrOutput = (await bundle!.generateHmrPatch([file]))!
9901006

9911007
await handleHmrOutput(hmrOutput, file)
9921008

9931009
if (hmrOutput.patch) {
994-
await build()
995-
logger.info(
996-
`${colors.green(`✓ rebuilt in ${displayTime(Date.now() - startTime)}`)}`,
997-
)
1010+
debounceBuild()
9981011
}
9991012
})
1013+
10001014
server.hot.on(
10011015
'vite:invalidate',
10021016
async ({ path: file, message, firstInvalidatedBy }) => {
1017+
// cancel the debounce build util the hmr invalidate is done.
1018+
cancelBuild()
10031019
const hmrOutput = (await bundle!.hmrInvalidate(
10041020
path.join(root, file),
10051021
firstInvalidatedBy,
@@ -1013,6 +1029,10 @@ async function buildEnvironment(
10131029
{ timestamp: true },
10141030
)
10151031
await handleHmrOutput(hmrOutput, file)
1032+
1033+
if (hmrOutput.patch) {
1034+
debounceBuild()
1035+
}
10161036
}
10171037
}
10181038
},

0 commit comments

Comments
 (0)