@@ -57,13 +57,11 @@ export function cachedTransformMiddleware(
5757 if ( ifNoneMatch ) {
5858 const moduleByEtag = server . moduleGraph . getModuleByEtag ( ifNoneMatch )
5959 if ( moduleByEtag ?. transformResult ?. etag === ifNoneMatch ) {
60- // For direct CSS requests, if the same CSS file is imported in a module,
60+ // For CSS requests, if the same CSS file is imported in a module,
6161 // the browser sends the request for the direct CSS request with the etag
6262 // from the imported CSS module. We ignore the etag in this case.
63- const mixedEtag =
64- ! req . headers . accept ?. includes ( 'text/css' ) &&
65- isDirectRequest ( moduleByEtag . url )
66- if ( ! mixedEtag ) {
63+ const maybeMixedEtag = isCSSRequest ( req . url ! )
64+ if ( ! maybeMixedEtag ) {
6765 debugCache ?.( `[304] ${ prettifyUrl ( req . url ! , server . config . root ) } ` )
6866 res . statusCode = 304
6967 return res . end ( )
@@ -176,14 +174,28 @@ export function transformMiddleware(
176174 // not valid browser import specifiers by the importAnalysis plugin.
177175 url = unwrapId ( url )
178176
179- // for CSS, we need to differentiate between normal CSS requests and
180- // imports
181- if (
182- isCSSRequest ( url ) &&
183- ! isDirectRequest ( url ) &&
184- req . headers . accept ?. includes ( 'text/css' )
185- ) {
186- url = injectQuery ( url , 'direct' )
177+ // for CSS, we differentiate between normal CSS requests and imports
178+ if ( isCSSRequest ( url ) ) {
179+ if (
180+ req . headers . accept ?. includes ( 'text/css' ) &&
181+ ! isDirectRequest ( url )
182+ ) {
183+ url = injectQuery ( url , 'direct' )
184+ }
185+
186+ // check if we can return 304 early for CSS requests. These aren't handled
187+ // by the cachedTransformMiddleware due to the browser possibly mixing the
188+ // etags of direct and imported CSS
189+ const ifNoneMatch = req . headers [ 'if-none-match' ]
190+ if (
191+ ifNoneMatch &&
192+ ( await server . moduleGraph . getModuleByUrl ( url , false ) )
193+ ?. transformResult ?. etag === ifNoneMatch
194+ ) {
195+ debugCache ?.( `[304] ${ prettifyUrl ( url , server . config . root ) } ` )
196+ res . statusCode = 304
197+ return res . end ( )
198+ }
187199 }
188200
189201 // resolve, load and transform using the plugin container
0 commit comments