diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 7bd7282aed712b..b4ec18d4157192 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -450,6 +450,18 @@ function optimizerResolvePlugin( const normalizedFsPath = normalizePath(fsPath) + if (asSrc && !options.scan && !SPECIAL_QUERY_RE.test(id)) { + const resolvedFsPath = tryFsResolve(fsPath, options) + const optimizedDep = depsOptimizer.metadata.depInfoList.find( + (depInfo) => + depInfo.src === + normalizePath(resolvedFsPath || normalizedFsPath), + ) + if (optimizedDep) { + return depsOptimizer.getOptimizedDepId(optimizedDep) + } + } + if (depsOptimizer.isOptimizedDepFile(normalizedFsPath)) { // Optimized files could not yet exist in disk, resolve to the full path // Inject the current browserHash version if the path doesn't have one diff --git a/playground/optimize-deps/__tests__/optimize-deps.spec.ts b/playground/optimize-deps/__tests__/optimize-deps.spec.ts index d6febaafad2c17..5b16169b449072 100644 --- a/playground/optimize-deps/__tests__/optimize-deps.spec.ts +++ b/playground/optimize-deps/__tests__/optimize-deps.spec.ts @@ -126,6 +126,24 @@ test('forced include', async () => { .toMatch(`[success]`) }) +test.runIf(isServe)( + 'optimizes a project source file imported relatively', + async () => { + await expect + .poll(() => page.textContent('.source-include')) + .toBe('source include') + + const metadata = readDepOptimizationMetadata() + const optimizedFile = metadata.optimized['./source-include.js'].file + const response = await fetch( + new URL('/source-include-entry.js', viteTestUrl), + ) + const source = await response.text() + + expect(source).toContain(`/node_modules/.vite/deps/${optimizedFile}`) + }, +) + test('import * from optimized dep', async () => { await expect.poll(() => page.textContent('.import-star')).toMatch(`[success]`) }) diff --git a/playground/optimize-deps/index.html b/playground/optimize-deps/index.html index 2e3b6607dabff7..dfeab677720d70 100644 --- a/playground/optimize-deps/index.html +++ b/playground/optimize-deps/index.html @@ -58,6 +58,10 @@