Skip to content

Commit

Permalink
fix(@angular-devkit/build-angular): handle HMR updates of global CSS …
Browse files Browse the repository at this point in the history
…when using Vite

This commit updates the Vite based dev-server to send updates for global styles using the HMR update instead of a full page reload when the the dev-server builder `hmr` option to be enabled.
  • Loading branch information
alan-agius4 committed Aug 17, 2023
1 parent c3c4853 commit b09ce57
Showing 1 changed file with 57 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import type { BuilderContext } from '@angular-devkit/architect';
import type { json } from '@angular-devkit/core';
import type { json, logging } from '@angular-devkit/core';
import type { OutputFile } from 'esbuild';
import { lookup as lookupMimeType } from 'mrmime';
import assert from 'node:assert';
Expand Down Expand Up @@ -89,23 +89,7 @@ export async function* serveWithVite(
}

if (server) {
// Invalidate any updated files
for (const [file, record] of generatedFiles) {
if (record.updated) {
const updatedModules = server.moduleGraph.getModulesByFile(file);
updatedModules?.forEach((m) => server?.moduleGraph.invalidateModule(m));
}
}

// Send reload command to clients
if (serverOptions.liveReload) {
context.logger.info('Reloading client(s)...');

server.ws.send({
type: 'full-reload',
path: '*',
});
}
handleUpdate(generatedFiles, server, serverOptions, context.logger);
} else {
// Setup server and start listening
const serverConfiguration = await setupServer(
Expand Down Expand Up @@ -140,6 +124,61 @@ export async function* serveWithVite(
}
}

function handleUpdate(
generatedFiles: Map<string, OutputFileRecord>,
server: ViteDevServer,
serverOptions: NormalizedDevServerOptions,
logger: logging.LoggerApi,
): void {
const updatedFiles: string[] = [];

// Invalidate any updated files
for (const [file, record] of generatedFiles) {
if (record.updated) {
updatedFiles.push(file);
const updatedModules = server.moduleGraph.getModulesByFile(file);
updatedModules?.forEach((m) => server?.moduleGraph.invalidateModule(m));
}
}

if (!updatedFiles.length) {
return;
}

if (serverOptions.hmr) {
if (updatedFiles.every((f) => f.endsWith('.css'))) {
const timestamp = Date.now();
server.ws.send({
type: 'update',
updates: updatedFiles.map((f) => {
const filePath = f.slice(1); // Remove leading slash.

return {
type: 'css-update',
timestamp,
path: filePath,
acceptedPath: filePath,
};
}),
});

logger.info('HMR update sent to client(s)...');

return;
}
}

// Send reload command to clients
if (serverOptions.liveReload) {
logger.info('Reloading client(s)...');

server.ws.send({
type: 'full-reload',
path: '*',
});
}
}

function analyzeResultFiles(
normalizePath: (id: string) => string,
resultFiles: OutputFile[],
Expand Down

0 comments on commit b09ce57

Please sign in to comment.