diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index b44ba0a048f189..7dda112b618d9e 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -42,7 +42,17 @@ export interface DepOptimizationOptions { } export interface DepOptimizationMetadata { + /** + * The main hash is determined by user config and dependency lockfiles. + * This is checked on server startup to avoid unncessary re-bundles. + */ hash: string + /** + * The browser hash is determined by the main hash plus additional dependencies + * discovered at runtime. This is used to invalidate browser requests to + * optimized deps. + */ + browserHash: string optimized: Record< string, { @@ -73,8 +83,10 @@ export async function optimizeDeps( } const dataPath = path.join(cacheDir, 'metadata.json') + const mainHash = getDepHash(root, config) const data: DepOptimizationMetadata = { - hash: getDepHash(root, config), + hash: mainHash, + browserHash: mainHash, optimized: {} } @@ -104,6 +116,12 @@ export async function optimizeDeps( missing = {} } + // update browser hash + data.browserHash = createHash('sha256') + .update(data.hash + JSON.stringify(deps)) + .digest('hex') + .substr(0, 8) + const missingIds = Object.keys(missing) if (missingIds.length) { throw new Error( diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index d79a8f976e2290..91f331a1935703 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -363,7 +363,7 @@ export function tryNodeResolve( // excluded from optimization // Inject a version query to npm deps so that the browser // can cache it without revalidation. - const versionHash = server._optimizeDepsMetadata?.hash + const versionHash = server._optimizeDepsMetadata?.browserHash if (versionHash) { resolved = injectQuery(resolved, `v=${versionHash}`) } @@ -387,7 +387,9 @@ export function tryOptimizedResolve( if (isOptimized) { return ( isOptimized.file + - `?v=${depData.hash}${isOptimized.needsInterop ? `&es-interop` : ``}` + `?v=${depData.browserHash}${ + isOptimized.needsInterop ? `&es-interop` : `` + }` ) } }