Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: invalidate data store module when dev server starts #12938

Merged
merged 2 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/strong-scissors-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes a bug where content collections would sometimes appear empty when first running astro dev
35 changes: 19 additions & 16 deletions packages/astro/src/content/vite-plugin-content-virtual-mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -59,8 +70,12 @@ export function astroContentVirtualModPlugin({
dataStoreFile = getDataStoreFile(settings, env.command === 'serve');
},
buildStart() {
// We defer adding the data store file to the watcher until the server is ready
devServer?.watcher.add(fileURLToPath(dataStoreFile));
if (devServer) {
// We defer adding the data store file to the watcher until the server is ready
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) {
Expand Down Expand Up @@ -164,29 +179,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);
}
});
},
Expand Down
Loading