Skip to content

Commit

Permalink
fix(optimizer): add separate hash for invalidating optimized deps
Browse files Browse the repository at this point in the history
between re-bundles
  • Loading branch information
yyx990803 committed Jan 28, 2021
1 parent 9ecf52b commit 216ae8e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
20 changes: 19 additions & 1 deletion packages/vite/src/node/optimizer/index.ts
Expand Up @@ -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,
{
Expand Down Expand Up @@ -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: {}
}

Expand Down Expand Up @@ -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(
Expand Down
6 changes: 4 additions & 2 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -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}`)
}
Expand All @@ -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` : ``
}`
)
}
}
Expand Down

0 comments on commit 216ae8e

Please sign in to comment.