diff --git a/packages/vite/src/node/plugins/workerImportMetaUrl.ts b/packages/vite/src/node/plugins/workerImportMetaUrl.ts index 0a7b34d4ff3dc8..3b0fdfb1e97548 100644 --- a/packages/vite/src/node/plugins/workerImportMetaUrl.ts +++ b/packages/vite/src/node/plugins/workerImportMetaUrl.ts @@ -7,6 +7,7 @@ import type { Plugin } from '../plugin' import { evalValue, injectQuery, transformStableResult } from '../utils' import type { ResolveFn } from '..' import { cleanUrl, slash } from '../../shared/utils' +import { getDepsOptimizer, optimizedDepInfoFromFile } from '../optimizer' import type { WorkerType } from './worker' import { WORKER_FILE_ID, workerFileToUrl } from './worker' import { fileToUrl } from './asset' @@ -114,6 +115,22 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin { asSrc: true, } + function tryOptimizedDepResolve(ssr: boolean, url: string, depId: string) { + const depsOptimizer = getDepsOptimizer(config, ssr) + + if (depsOptimizer?.isOptimizedDepFile(depId)) { + const depFile = cleanUrl(depId) + const info = optimizedDepInfoFromFile(depsOptimizer.metadata, depFile) + const depSrc = info?.src + if (depSrc) { + const resolvedFile = path.resolve(path.dirname(depSrc), url) + return tryFsResolve(resolvedFile, fsResolveOptions) + } + } + + return undefined + } + return { name: 'vite:worker-import-meta-url', @@ -148,10 +165,14 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin { s ||= new MagicString(code) const workerType = getWorkerType(code, cleanString, endIndex) const url = rawUrl.slice(1, -1) + let file: string | undefined if (url[0] === '.') { file = path.resolve(path.dirname(id), url) - file = tryFsResolve(file, fsResolveOptions) ?? file + file = + tryFsResolve(file, fsResolveOptions) ?? + tryOptimizedDepResolve(options?.ssr === true, url, id) ?? + file } else { workerResolver ??= config.createResolver({ extensions: [],