diff --git a/.changeset/strong-scissors-sip.md b/.changeset/strong-scissors-sip.md new file mode 100644 index 000000000000..7bb1aa985929 --- /dev/null +++ b/.changeset/strong-scissors-sip.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes a bug where content collections would sometimes appear empty when first running astro dev diff --git a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts index e0468c654f85..15c148ae1cd5 100644 --- a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts +++ b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts @@ -46,6 +46,17 @@ interface AstroContentVirtualModPluginParams { fs: typeof nodeFs; } +function invalidateDataStore(server: ViteDevServer) { + const module = server.moduleGraph.getModuleById(RESOLVED_DATA_STORE_VIRTUAL_ID); + if (module) { + server.moduleGraph.invalidateModule(module); + } + server.ws.send({ + type: 'full-reload', + path: '*', + }); +} + export function astroContentVirtualModPlugin({ settings, fs, @@ -60,7 +71,9 @@ export function astroContentVirtualModPlugin({ }, buildStart() { // We defer adding the data store file to the watcher until the server is ready - devServer?.watcher.add(fileURLToPath(dataStoreFile)); + devServer.watcher.add(fileURLToPath(dataStoreFile)); + // Manually invalidate the data store to avoid a race condition in file watching + invalidateDataStore(devServer); }, async resolveId(id) { if (id === VIRTUAL_MODULE_ID) { @@ -164,29 +177,17 @@ export function astroContentVirtualModPlugin({ configureServer(server) { devServer = server; const dataStorePath = fileURLToPath(dataStoreFile); - - function invalidateDataStore() { - const module = server.moduleGraph.getModuleById(RESOLVED_DATA_STORE_VIRTUAL_ID); - if (module) { - server.moduleGraph.invalidateModule(module); - } - server.ws.send({ - type: 'full-reload', - path: '*', - }); - } - // If the datastore file changes, invalidate the virtual module server.watcher.on('add', (addedPath) => { if (addedPath === dataStorePath) { - invalidateDataStore(); + invalidateDataStore(server); } }); server.watcher.on('change', (changedPath) => { if (changedPath === dataStorePath) { - invalidateDataStore(); + invalidateDataStore(server); } }); },