@@ -2,8 +2,8 @@ import path from 'node:path'
22import MagicString from 'magic-string'
33import type { OutputChunk , RolldownPlugin , RollupError } from 'rolldown'
44import type { ChunkMetadata } from 'types/metadata'
5+ import { type ImportSpecifier , init , parse } from 'es-module-lexer'
56import type { ResolvedConfig } from '../config'
6- import type { Plugin } from '../plugin'
77import { ENV_ENTRY , ENV_PUBLIC_PATH } from '../constants'
88import {
99 encodeURIPath ,
@@ -214,33 +214,46 @@ export async function workerFileToUrl(
214214 return encodeWorkerAssetFileName ( fileName , workerMap )
215215}
216216
217- export function webWorkerPostPlugin ( ) : Plugin {
217+ export function webWorkerPostPlugin ( ) : RolldownPlugin {
218218 return {
219219 name : 'vite:worker-post' ,
220- // TODO: resolveImportMeta is not supported yet, use transform hook for now
221- // resolveImportMeta(property, { format }) {
222- // // document is undefined in the worker, so we need to avoid it in iife
223- // if (format === 'iife') {
224- // // compiling import.meta
225- // if (!property) {
226- // // rollup only supports `url` property. we only support `url` property as well.
227- // // https://github.com/rollup/rollup/blob/62b648e1cc6a1f00260bb85aa2050097bb4afd2b/src/ast/nodes/MetaProperty.ts#L164-L173
228- // return `{
229- // url: self.location.href
230- // }`
231- // }
232- // // compiling import.meta.url
233- // if (property === 'url') {
234- // return 'self.location.href'
235- // }
236- // }
220+ transform : {
221+ filter : {
222+ code : 'import.meta.url' ,
223+ } ,
224+ async handler ( code , id ) {
225+ // document is undefined in the worker, so we need to avoid import.meta.url in iife
226+ if ( this . environment . config . worker . format === 'iife' ) {
227+ await init
228+
229+ let imports : readonly ImportSpecifier [ ]
230+ try {
231+ imports = parse ( code ) [ 0 ]
232+ } catch {
233+ // ignore if parse fails
234+ return
235+ }
237236
238- // return null
239- // },
240- transform ( code ) {
241- if ( code . includes ( 'import.meta.url' ) ) {
242- return code . replaceAll ( 'import.meta.url' , 'self.location.href' )
243- }
237+ let s : MagicString | undefined
238+ for ( const { s : start , e : end , d : dynamicIndex } of imports ) {
239+ // is import.meta
240+ if ( dynamicIndex === - 2 ) {
241+ const prop = code . slice ( end , end + 4 )
242+ if ( prop === '.url' ) {
243+ s ||= new MagicString ( code )
244+ s . overwrite ( start , end + 4 , 'self.location.href' )
245+ }
246+ }
247+ }
248+
249+ if ( ! s ) return
250+
251+ return {
252+ code : s . toString ( ) ,
253+ map : s . generateMap ( { hires : 'boundary' , source : id } ) ,
254+ }
255+ }
256+ } ,
244257 } ,
245258 }
246259}
0 commit comments