@@ -59,6 +59,7 @@ import { throwOutdatedRequest } from './optimizedDeps'
59
59
import { isCSSRequest , isDirectCSSRequest } from './css'
60
60
import { browserExternalId } from './resolve'
61
61
import { serializeDefine } from './define'
62
+ import { WORKER_FILE_ID } from './worker'
62
63
63
64
const debug = createDebugger ( 'vite:import-analysis' )
64
65
@@ -685,12 +686,17 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
685
686
const acceptedUrls = mergeAcceptedUrls ( orderedAcceptedUrls )
686
687
const acceptedExports = mergeAcceptedUrls ( orderedAcceptedExports )
687
688
688
- if ( hasEnv ) {
689
+ // While we always expect to work with ESM, a classic worker is the only
690
+ // case where it's not ESM and we need to avoid injecting ESM-specific code
691
+ const isClassicWorker =
692
+ importer . includes ( WORKER_FILE_ID ) && importer . includes ( 'type=classic' )
693
+
694
+ if ( hasEnv && ! isClassicWorker ) {
689
695
// inject import.meta.env
690
696
str ( ) . prepend ( getEnv ( ssr ) )
691
697
}
692
698
693
- if ( hasHMR && ! ssr ) {
699
+ if ( hasHMR && ! ssr && ! isClassicWorker ) {
694
700
debugHmr ?.(
695
701
`${
696
702
isSelfAccepting
@@ -712,9 +718,13 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
712
718
}
713
719
714
720
if ( needQueryInjectHelper ) {
715
- str ( ) . prepend (
716
- `import { injectQuery as __vite__injectQuery } from "${ clientPublicPath } ";` ,
717
- )
721
+ if ( isClassicWorker ) {
722
+ str ( ) . append ( '\n' + __vite__injectQuery . toString ( ) )
723
+ } else {
724
+ str ( ) . prepend (
725
+ `import { injectQuery as __vite__injectQuery } from "${ clientPublicPath } ";` ,
726
+ )
727
+ }
718
728
}
719
729
720
730
// normalize and rewrite accepted urls
@@ -1009,3 +1019,19 @@ export function transformCjsImport(
1009
1019
return lines . join ( '; ' )
1010
1020
}
1011
1021
}
1022
+
1023
+ // Copied from `client/client.ts`. Only needed so we can inline inject this function for classic workers.
1024
+ function __vite__injectQuery ( url : string , queryToInject : string ) : string {
1025
+ // skip urls that won't be handled by vite
1026
+ if ( url [ 0 ] !== '.' && url [ 0 ] !== '/' ) {
1027
+ return url
1028
+ }
1029
+
1030
+ // can't use pathname from URL since it may be relative like ../
1031
+ const pathname = url . replace ( / [ ? # ] .* $ / s, '' )
1032
+ const { search, hash } = new URL ( url , 'http://vitejs.dev' )
1033
+
1034
+ return `${ pathname } ?${ queryToInject } ${ search ? `&` + search . slice ( 1 ) : '' } ${
1035
+ hash || ''
1036
+ } `
1037
+ }
0 commit comments