Skip to content

fix: skip watching non-existent public directory#21864

Open
patil-amrut wants to merge 1 commit intovitejs:mainfrom
patil-amrut:fix/missing-public-dir-breaks-hmr
Open

fix: skip watching non-existent public directory#21864
patil-amrut wants to merge 1 commit intovitejs:mainfrom
patil-amrut:fix/missing-public-dir-breaks-hmr

Conversation

@patil-amrut
Copy link
Copy Markdown

When publicDir is configured but the directory does not exist, initPublicFiles returns an empty Set (truthy), causing the non-existent path to be added to chokidar's watch list. This silently breaks HMR as chokidar fails to detect file changes.

Check publicFiles.size instead of just publicFiles to ensure only existing, non-empty public directories are watched.

Fixes #19864

What does this PR solve?

Fixes a bug where Hot Module Replacement (HMR) silently breaks when publicDir is configured in vite.config.js but the specified directory does not exist on disk.

Why was this approach chosen?

The root cause was in the file watcher setup in packages/vite/src/node/server/index.ts. When publicDir is configured but doesn't exist:

  1. initPublicFiles() calls recursiveReaddir() which returns [] for non-existent directories
  2. This creates an empty Set (publicFiles = new Set([]))
  3. Empty Sets are truthy in JavaScript, so the condition publicDir && publicFiles evaluates to true
  4. The non-existent path gets added to chokidar's watch list, silently breaking HMR

The fix checks publicFiles?.size instead of just publicFiles to ensure only existing, non-empty public directories are watched.

Testing

  • Added a unit test that verifies non-existent public directories are not added to the watcher
  • All existing tests continue to pass (727 tests across 53 files)
  • Lint passes with no issues

Fixes #19864

When publicDir is configured but the directory does not exist,
initPublicFiles returns an empty Set (truthy), causing the
non-existent path to be added to chokidar's watch list. This
silently breaks HMR as chokidar fails to detect file changes.

Check publicFiles.size instead of just publicFiles to ensure
only existing, non-empty public directories are watched.

Fixes vitejs#19864
Copy link
Copy Markdown
Member

@sapphi-red sapphi-red left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The non-existent path gets added to chokidar's watch list, silently breaking HMR

There’s a logical leap here. Could you elaborate?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Missing configured public folder silently breaks HMR

2 participants