-
Notifications
You must be signed in to change notification settings - Fork 13
fix(vite): stop swallowing HMR updates for non-component resources #197
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6b07c3b
fix(vite): stop swallowing HMR updates for non-component resources
Brooooooklyn 66f5a8e
fix review: remove synthetic watcher emit, fix test setup
Brooooooklyn d7e277b
fix: resolve oxlint type-check errors in HMR tests
Brooooooklyn e3a9004
fix: prune stale resourceToComponent entries and fix Windows CI
Brooooooklyn d3c7bde
fix: re-add pruned resources to Vite watcher
Brooooooklyn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,276 @@ | ||
| /** | ||
| * Tests for handleHotUpdate behavior (Issue #185). | ||
| * | ||
| * The plugin's handleHotUpdate hook must distinguish between: | ||
| * 1. Component resource files (templates/styles) → handled by custom fs.watch, return [] | ||
| * 2. Non-component files (global CSS, etc.) → let Vite handle normally | ||
| * | ||
| * Previously, the plugin returned [] for ALL .css/.html files, which swallowed | ||
| * HMR updates for global stylesheets and prevented PostCSS/Tailwind from | ||
| * processing changes. | ||
| */ | ||
| import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' | ||
| import { tmpdir } from 'node:os' | ||
| import { join } from 'node:path' | ||
|
|
||
| import type { Plugin, ModuleNode, HmrContext } from 'vite' | ||
| import { normalizePath } from 'vite' | ||
| import { afterAll, beforeAll, describe, it, expect, vi } from 'vitest' | ||
|
|
||
| import { angular } from '../vite-plugin/index.js' | ||
|
|
||
| let tempDir: string | ||
| let appDir: string | ||
| let templatePath: string | ||
| let stylePath: string | ||
|
|
||
| beforeAll(() => { | ||
| tempDir = mkdtempSync(join(tmpdir(), 'hmr-test-')) | ||
| appDir = join(tempDir, 'src', 'app') | ||
| mkdirSync(appDir, { recursive: true }) | ||
|
|
||
| templatePath = join(appDir, 'app.component.html') | ||
| stylePath = join(appDir, 'app.component.css') | ||
|
|
||
| writeFileSync(templatePath, '<h1>Hello</h1>') | ||
| writeFileSync(stylePath, 'h1 { color: red; }') | ||
| }) | ||
|
|
||
| afterAll(() => { | ||
| rmSync(tempDir, { recursive: true, force: true }) | ||
| }) | ||
|
|
||
| function getAngularPlugin() { | ||
| const plugin = angular({ liveReload: true }).find( | ||
| (candidate) => candidate.name === '@oxc-angular/vite', | ||
| ) | ||
|
|
||
| if (!plugin) { | ||
| throw new Error('Failed to find @oxc-angular/vite plugin') | ||
| } | ||
|
|
||
| return plugin | ||
| } | ||
|
|
||
| function createMockServer() { | ||
| const wsMessages: any[] = [] | ||
| const unwatchedFiles = new Set<string>() | ||
|
|
||
| return { | ||
| watcher: { | ||
| unwatch(file: string) { | ||
| unwatchedFiles.add(file) | ||
| }, | ||
| on: vi.fn(), | ||
| emit: vi.fn(), | ||
| }, | ||
| ws: { | ||
| send(msg: any) { | ||
| wsMessages.push(msg) | ||
| }, | ||
| on: vi.fn(), | ||
| }, | ||
| moduleGraph: { | ||
| getModuleById: vi.fn(() => null), | ||
| invalidateModule: vi.fn(), | ||
| }, | ||
| middlewares: { | ||
| use: vi.fn(), | ||
| }, | ||
| config: { | ||
| root: tempDir, | ||
| }, | ||
| _wsMessages: wsMessages, | ||
| _unwatchedFiles: unwatchedFiles, | ||
| } | ||
| } | ||
|
|
||
| function createMockHmrContext( | ||
| file: string, | ||
| modules: Partial<ModuleNode>[] = [], | ||
| server?: any, | ||
| ): HmrContext { | ||
| return { | ||
| file, | ||
| timestamp: Date.now(), | ||
| modules: modules as ModuleNode[], | ||
| read: async () => '', | ||
| server: server ?? createMockServer(), | ||
| } as HmrContext | ||
| } | ||
|
|
||
| async function callHandleHotUpdate( | ||
| plugin: Plugin, | ||
| ctx: HmrContext, | ||
| ): Promise<ModuleNode[] | void | undefined> { | ||
| if (typeof plugin.handleHotUpdate === 'function') { | ||
| return (plugin.handleHotUpdate as Function).call(plugin, ctx) | ||
| } | ||
| return undefined | ||
| } | ||
|
|
||
| async function callPluginHook<TArgs extends unknown[], TResult>( | ||
| hook: | ||
| | { | ||
| handler: (...args: TArgs) => TResult | ||
| } | ||
| | ((...args: TArgs) => TResult) | ||
| | undefined, | ||
| ...args: TArgs | ||
| ): Promise<TResult | undefined> { | ||
| if (!hook) return undefined | ||
| if (typeof hook === 'function') return hook(...args) | ||
| return hook.handler(...args) | ||
| } | ||
|
|
||
| /** | ||
| * Set up a plugin through the full Vite lifecycle so that internal state | ||
| * (watchMode, viteServer, resourceToComponent, componentIds) is populated. | ||
| */ | ||
| async function setupPluginWithServer(plugin: Plugin) { | ||
| const mockServer = createMockServer() | ||
|
|
||
| // config() sets watchMode = true when command === 'serve' | ||
| await callPluginHook( | ||
| plugin.config as Plugin['config'], | ||
| {} as any, | ||
| { | ||
| command: 'serve', | ||
| mode: 'development', | ||
| } as any, | ||
| ) | ||
|
|
||
| // configResolved() stores the resolved config | ||
| await callPluginHook( | ||
| plugin.configResolved as Plugin['configResolved'], | ||
| { | ||
| build: {}, | ||
| isProduction: false, | ||
| } as any, | ||
| ) | ||
|
|
||
| // configureServer() sets up the custom watcher and stores viteServer | ||
| if (typeof plugin.configureServer === 'function') { | ||
| await (plugin.configureServer as Function)(mockServer) | ||
| } | ||
|
|
||
| // Replace the real fs.watch-based watcher with a no-op to avoid EPERM | ||
| // errors on Windows when temp files are cleaned up. resourceToComponent | ||
| // is populated in transform *before* watchFn is called, so the map is | ||
| // still correctly populated for handleHotUpdate tests. | ||
| ;(mockServer as any).__angularWatchTemplate = () => {} | ||
|
|
||
| return mockServer | ||
| } | ||
|
|
||
| /** | ||
| * Transform a component that references external template + style files, | ||
| * populating resourceToComponent and componentIds. | ||
| */ | ||
| async function transformComponent(plugin: Plugin) { | ||
| const componentFile = join(appDir, 'app.component.ts') | ||
| const componentSource = ` | ||
| import { Component } from '@angular/core'; | ||
|
|
||
| @Component({ | ||
| selector: 'app-root', | ||
| templateUrl: './app.component.html', | ||
| styleUrls: ['./app.component.css'], | ||
| }) | ||
| export class AppComponent {} | ||
| ` | ||
|
|
||
| if (!plugin.transform || typeof plugin.transform === 'function') { | ||
| throw new Error('Expected plugin transform handler') | ||
| } | ||
|
|
||
| await plugin.transform.handler.call( | ||
| { error() {}, warn() {} } as any, | ||
| componentSource, | ||
| componentFile, | ||
| ) | ||
| } | ||
|
|
||
| describe('handleHotUpdate - Issue #185', () => { | ||
| it('should let non-component CSS files pass through to Vite HMR', async () => { | ||
| const plugin = getAngularPlugin() | ||
| await setupPluginWithServer(plugin) | ||
|
|
||
| // A global CSS file (not referenced by any component's styleUrls) | ||
| const globalCssFile = normalizePath(join(tempDir, 'src', 'styles.css')) | ||
| const mockModules = [{ id: globalCssFile }] | ||
| const ctx = createMockHmrContext(globalCssFile, mockModules) | ||
|
|
||
| const result = await callHandleHotUpdate(plugin, ctx) | ||
|
|
||
| // Non-component CSS should NOT be swallowed — either undefined (pass through) | ||
| // or the original modules array, but NOT an empty array | ||
| if (result !== undefined) { | ||
| expect(result).toEqual(mockModules) | ||
| } | ||
| }) | ||
|
|
||
| it('should return [] for component CSS files managed by custom watcher', async () => { | ||
| const plugin = getAngularPlugin() | ||
| const mockServer = await setupPluginWithServer(plugin) | ||
| await transformComponent(plugin) | ||
|
|
||
| // The component's CSS file IS in resourceToComponent | ||
| const componentCssFile = normalizePath(stylePath) | ||
| const mockModules = [{ id: componentCssFile }] | ||
| const ctx = createMockHmrContext(componentCssFile, mockModules, mockServer) | ||
|
|
||
| const result = await callHandleHotUpdate(plugin, ctx) | ||
|
|
||
| // Component resources MUST be swallowed (return []) | ||
| expect(result).toEqual([]) | ||
| }) | ||
|
|
||
| it('should return [] for component template HTML files managed by custom watcher', async () => { | ||
| const plugin = getAngularPlugin() | ||
| const mockServer = await setupPluginWithServer(plugin) | ||
| await transformComponent(plugin) | ||
|
|
||
| // The component's HTML template IS in resourceToComponent | ||
| const componentHtmlFile = normalizePath(templatePath) | ||
| const ctx = createMockHmrContext(componentHtmlFile, [{ id: componentHtmlFile }], mockServer) | ||
|
|
||
| const result = await callHandleHotUpdate(plugin, ctx) | ||
|
|
||
| // Component templates MUST be swallowed (return []) | ||
| expect(result).toEqual([]) | ||
| }) | ||
|
|
||
| it('should not swallow non-resource HTML files', async () => { | ||
| const plugin = getAngularPlugin() | ||
| await setupPluginWithServer(plugin) | ||
|
|
||
| // index.html is NOT a component template | ||
| const indexHtml = normalizePath(join(tempDir, 'index.html')) | ||
| const mockModules = [{ id: indexHtml }] | ||
| const ctx = createMockHmrContext(indexHtml, mockModules) | ||
|
|
||
| const result = await callHandleHotUpdate(plugin, ctx) | ||
|
|
||
| // Non-component HTML should pass through, not be swallowed | ||
| if (result !== undefined) { | ||
| expect(result).toEqual(mockModules) | ||
| } | ||
| }) | ||
|
|
||
| it('should pass through non-style/template files unchanged', async () => { | ||
| const plugin = getAngularPlugin() | ||
| await setupPluginWithServer(plugin) | ||
|
|
||
| const utilFile = normalizePath(join(tempDir, 'src', 'utils.ts')) | ||
| const mockModules = [{ id: utilFile }] | ||
| const ctx = createMockHmrContext(utilFile, mockModules) | ||
|
|
||
| const result = await callHandleHotUpdate(plugin, ctx) | ||
|
|
||
| // Non-Angular .ts files should pass through with their modules | ||
| if (result !== undefined) { | ||
| expect(result).toEqual(mockModules) | ||
| } | ||
| }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.