Skip to content

Commit

Permalink
fix(vite-plugin-angular): handle emulated encapsulation component styles
Browse files Browse the repository at this point in the history
  • Loading branch information
mattlewis92 committed Jan 6, 2025
1 parent e013eb3 commit 647ccb9
Showing 1 changed file with 41 additions and 7 deletions.
48 changes: 41 additions & 7 deletions packages/vite-plugin-angular/src/lib/angular-vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
ResolvedConfig,
Connect,
} from 'vite';
import { encapsulateStyle } from '@angular/compiler';

import { createCompilerPlugin } from './compiler-plugin.js';
import {
Expand Down Expand Up @@ -368,17 +369,14 @@ export function angular(options?: PluginOptions): Plugin[] {
);
if (pluginOptions.liveReload && isDirect?.id && isDirect.file) {
const isComponentStyle =
isDirect.type === 'css' && isDirect.id?.includes('ngcomp=');
isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);
if (isComponentStyle) {
const encapsulation = new URL(
isDirect.id,
'http://localhost'
).searchParams.get('e');
const { encapsulation } = getComponentStyleSheetMeta(isDirect.id);

// Track if the component uses ShadowDOM encapsulation (3 = ViewEncapsulation.ShadowDom)
// Track if the component uses ShadowDOM encapsulation
// Shadow DOM components currently require a full reload.
// Vite's CSS hot replacement does not support shadow root searching.
if (encapsulation !== '3') {
if (encapsulation !== 'shadow') {
ctx.server.ws.send({
type: 'update',
updates: [
Expand Down Expand Up @@ -519,6 +517,20 @@ export function angular(options?: PluginOptions): Plugin[] {
return;
}

/**
* Encapsulate component stylesheets that use emulated encapsulation
*/
if (isComponentStyleSheet(id)) {
const { encapsulation, componentId } = getComponentStyleSheetMeta(id);
if (encapsulation === 'emulated' && componentId) {
const encapsulated = encapsulateStyle(code, componentId);
return {
code: encapsulated,
map: null,
};
}
}

if (TS_EXT_REGEX.test(id)) {
if (id.includes('.ts?')) {
// Strip the query string off the ID
Expand Down Expand Up @@ -955,3 +967,25 @@ function markModuleSelfAccepting(mod: ModuleNode): ModuleNode {
isSelfAccepting: true,
} as ModuleNode;
}

function isComponentStyleSheet(id: string): boolean {
return id.includes('ngcomp=');
}

function getComponentStyleSheetMeta(id: string): {
componentId: string;
encapsulation: 'emulated' | 'shadow' | 'none';
} {
const params = new URL(id, 'http://localhost').searchParams;
const encapsulationMapping = {
'0': 'emulated',
'2': 'none',
'3': 'shadow',
};
return {
componentId: params.get('ngcomp')!,
encapsulation: encapsulationMapping[
params.get('e') as keyof typeof encapsulationMapping
] as 'emulated' | 'shadow' | 'none',
};
}

0 comments on commit 647ccb9

Please sign in to comment.