-
Notifications
You must be signed in to change notification settings - Fork 19
fix(vite): rebuild component styles when a transitive preprocessor dependency changes #425
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
Open
Alexays
wants to merge
1
commit into
voidzero-dev:main
Choose a base branch
from
Alexays:fix/transitive-style-dep-hmr
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
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,203 @@ | ||
| /** | ||
| * Tests HMR for transitive style dependencies. | ||
| * | ||
| * A component styleUrl compiled through a CSS preprocessor can pull in shared | ||
| * files (Sass partials via `@use` / `@import` / `meta.load-css`, Less imports, | ||
| * ...). `preprocessCSS` reports them in `deps`; the plugin must invalidate the | ||
| * compiled style and dispatch component HMR when one of them changes, for every | ||
| * component whose style is built on top of it. | ||
| */ | ||
| import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' | ||
| import { tmpdir } from 'node:os' | ||
| import { join } from 'node:path' | ||
|
|
||
| import type { Plugin, ModuleNode, HmrContext } from 'vite' | ||
| import { resolveConfig } 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 sharedScssPath: string | ||
| let firstComponentPath: string | ||
| let secondComponentPath: string | ||
|
|
||
| const componentSource = (selector: string, styleUrl: string) => ` | ||
| import { Component } from '@angular/core'; | ||
|
|
||
| @Component({ | ||
| selector: '${selector}', | ||
| template: '<h1>Hello</h1>', | ||
| styleUrls: ['./${styleUrl}'], | ||
| }) | ||
| export class AppComponent {} | ||
| ` | ||
|
|
||
| beforeAll(() => { | ||
| // realpath: Sass canonicalizes loaded URLs (macOS /var -> /private/var), | ||
| // and watcher events use canonical paths too. | ||
| tempDir = realpathSync(mkdtempSync(join(tmpdir(), 'style-deps-hmr-test-'))) | ||
| appDir = join(tempDir, 'src', 'app') | ||
| mkdirSync(appDir, { recursive: true }) | ||
|
|
||
| sharedScssPath = join(appDir, '_shared.scss') | ||
| firstComponentPath = join(appDir, 'first.component.ts') | ||
| secondComponentPath = join(appDir, 'second.component.ts') | ||
|
|
||
| writeFileSync(sharedScssPath, 'h1 { color: red; }') | ||
| writeFileSync(join(appDir, 'first.component.scss'), "@use './shared';") | ||
| writeFileSync(join(appDir, 'second.component.scss'), "@use './shared';") | ||
| writeFileSync(firstComponentPath, componentSource('app-first', 'first.component.scss')) | ||
| writeFileSync(secondComponentPath, componentSource('app-second', 'second.component.scss')) | ||
| }) | ||
|
|
||
| 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[] = [] | ||
|
|
||
| return { | ||
| watcher: { | ||
| unwatch: vi.fn(), | ||
| 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, | ||
| } | ||
| } | ||
|
|
||
| function createMockHmrContext(file: string, server: any): HmrContext { | ||
| return { | ||
| file, | ||
| timestamp: Date.now(), | ||
| modules: [{ id: file } as ModuleNode], | ||
| read: async () => '', | ||
| server, | ||
| } as HmrContext | ||
| } | ||
|
|
||
| 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) | ||
| } | ||
|
|
||
| async function setupPluginWithServer(plugin: Plugin) { | ||
| const mockServer = createMockServer() | ||
|
|
||
| await callPluginHook( | ||
| plugin.config as Plugin['config'], | ||
| {} as any, | ||
| { | ||
| command: 'serve', | ||
| mode: 'development', | ||
| } as any, | ||
| ) | ||
|
|
||
| // A real resolved config: preprocessCSS needs one to run Sass and report | ||
| // the partials it loaded in `deps`. | ||
| const resolved = await resolveConfig( | ||
| { configFile: false, root: tempDir, logLevel: 'silent' }, | ||
| 'serve', | ||
| ) | ||
| await callPluginHook(plugin.configResolved as Plugin['configResolved'], resolved as any) | ||
|
|
||
| if (typeof plugin.configureServer === 'function') { | ||
| await (plugin.configureServer as Function)(mockServer) | ||
| } | ||
|
|
||
| ;(mockServer as any).__angularWatchTemplate = () => {} | ||
|
|
||
| return mockServer | ||
| } | ||
|
|
||
| async function transformComponent(plugin: Plugin, source: string, path: string) { | ||
| if (!plugin.transform || typeof plugin.transform === 'function') { | ||
| throw new Error('Expected plugin transform handler') | ||
| } | ||
|
|
||
| await plugin.transform.handler.call({ error() {}, warn() {} } as any, source, path) | ||
| } | ||
|
|
||
| describe('handleHotUpdate for transitive style dependencies', () => { | ||
| it('dispatches HMR to every component whose style uses a changed Sass partial', async () => { | ||
| const plugin = getAngularPlugin() | ||
| const mockServer = await setupPluginWithServer(plugin) | ||
|
|
||
| await transformComponent( | ||
| plugin, | ||
| componentSource('app-first', 'first.component.scss'), | ||
| firstComponentPath, | ||
| ) | ||
| await transformComponent( | ||
| plugin, | ||
| componentSource('app-second', 'second.component.scss'), | ||
| secondComponentPath, | ||
| ) | ||
|
|
||
| const ctx = createMockHmrContext(sharedScssPath, mockServer) | ||
| const result = await (plugin.handleHotUpdate as Function).call(plugin, ctx) | ||
|
|
||
| // Handled by the plugin: no modules left for Vite's default pipeline. | ||
| expect(result).toEqual([]) | ||
|
|
||
| // Both owning components received a component-update event. | ||
| const updates = mockServer._wsMessages.filter( | ||
| (msg) => msg?.event === 'angular:component-update', | ||
| ) | ||
| const updatedIds = updates.map((msg) => decodeURIComponent(msg.data.id)) | ||
| expect(updatedIds.some((id) => id.startsWith(firstComponentPath))).toBe(true) | ||
| expect(updatedIds.some((id) => id.startsWith(secondComponentPath))).toBe(true) | ||
| }) | ||
|
|
||
| it('leaves untracked stylesheets to Vite', async () => { | ||
| const plugin = getAngularPlugin() | ||
| const mockServer = await setupPluginWithServer(plugin) | ||
|
|
||
| const untracked = join(appDir, 'not-a-dep.scss') | ||
| writeFileSync(untracked, 'h2 { color: blue; }') | ||
| const ctx = createMockHmrContext(untracked, mockServer) | ||
| const result = await (plugin.handleHotUpdate as Function).call(plugin, ctx) | ||
|
|
||
| expect(result).toBe(ctx.modules) | ||
| }) | ||
| }) |
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we really need this?