Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,11 +200,23 @@ export function createDepsOptimizer(
try {
debug?.(colors.green(`scanning for dependencies...`))

discover = discoverProjectDependencies(
devToScanEnvironment(environment),
)
const deps = await discover.result
discover = undefined
let deps: Record<string, string>
try {
discover = discoverProjectDependencies(
devToScanEnvironment(environment),
)
deps = await discover.result
discover = undefined
} catch (e) {
environment.logger.error(
colors.red(
'(!) Failed to run dependency scan. ' +
'Skipping dependency pre-bundling. ' +
e.stack,
),
)
return
}
Comment on lines +210 to +219
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part of the change just adds some context to the error. It looks like
image


const manuallyIncluded = Object.keys(manuallyIncludedDepsInfo)
discoveredDepsWhileScanning.push(
Expand Down
146 changes: 67 additions & 79 deletions packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,17 +123,17 @@ export function scanImports(environment: ScanEnvironment): {
}>
} {
const start = performance.now()
const deps: Record<string, string> = {}
const missing: Record<string, string> = {}
let entries: string[]

const { config } = environment

const scanContext = { cancelled: false }
const esbuildContext: Promise<BuildContext | undefined> = computeEntries(
environment,
).then((computedEntries) => {
entries = computedEntries
let esbuildContext: Promise<BuildContext | undefined> | undefined
async function cancel() {
scanContext.cancelled = true
return esbuildContext?.then((context) => context?.cancel())
}

async function scan() {
const entries = await computeEntries(environment)
if (!entries.length) {
if (!config.optimizeDeps.entries && !config.optimizeDeps.include) {
environment.logger.warn(
Expand All @@ -153,82 +153,73 @@ export function scanImports(environment: ScanEnvironment): {
.map((entry) => `\n ${colors.dim(entry)}`)
.join('')}`,
)
return prepareEsbuildScanner(
environment,
entries,
deps,
missing,
scanContext,
)
})
const deps: Record<string, string> = {}
const missing: Record<string, string> = {}

let context: BuildContext | undefined
try {
esbuildContext = prepareEsbuildScanner(
environment,
entries,
deps,
missing,
)
context = await esbuildContext
if (scanContext.cancelled) return

const result = esbuildContext
.then((context) => {
function disposeContext() {
return context?.dispose().catch((e) => {
environment.logger.error('Failed to dispose esbuild context', {
error: e,
})
})
}
if (!context || scanContext.cancelled) {
disposeContext()
return { deps: {}, missing: {} }
}
return context
.rebuild()
.then(() => {
return {
// Ensure a fixed order so hashes are stable and improve logs
deps: orderedDependencies(deps),
missing,
}
})
.finally(() => {
return disposeContext()
})
})
.catch(async (e) => {
if (e.errors && e.message.includes('The build was canceled')) {
// esbuild logs an error when cancelling, but this is expected so
// return an empty result instead
return { deps: {}, missing: {} }
}
try {
await context!.rebuild()
return {
// Ensure a fixed order so hashes are stable and improve logs
deps: orderedDependencies(deps),
missing,
}
} catch (e) {
if (e.errors && e.message.includes('The build was canceled')) {
// esbuild logs an error when cancelling, but this is expected so
// return an empty result instead
return { deps: {}, missing: {} }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this return undefined like in line 168? Now that there is a fallback at 222, maybe it is good to normalize it. Or if not, return { deps: {}, missing: {} } everywhere instead of the fallback

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense. I've updated to return undefined.

}

const prependMessage = colors.red(`\
const prependMessage = colors.red(`\
Failed to scan for dependencies from entries:
${entries.join('\n')}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the place the TypeError: Cannot read properties of undefined (reading 'join') error was happening.
When computeEntries throws an error, entries = computedEntries in the then after computeEntries is not executed and entries will be kept as undefined.

The old code was not clear which variable lives at which part of the code. TypeScript is not good with analyzing code flow that uses promise + then + temp variable.
I refactored the code to use a single async function so that the code flow is a straight line. This should be easier to understand for both us and TypeScript.


`)
if (e.errors) {
const msgs = await formatMessages(e.errors, {
kind: 'error',
color: true,
})
e.message = prependMessage + msgs.join('\n')
} else {
e.message = prependMessage + e.message
}
throw e
})
.finally(() => {
if (debug) {
const duration = (performance.now() - start).toFixed(2)
const depsStr =
Object.keys(orderedDependencies(deps))
.sort()
.map((id) => `\n ${colors.cyan(id)} -> ${colors.dim(deps[id])}`)
.join('') || colors.dim('no dependencies found')
debug(`Scan completed in ${duration}ms: ${depsStr}`)
if (e.errors) {
const msgs = await formatMessages(e.errors, {
kind: 'error',
color: true,
})
e.message = prependMessage + msgs.join('\n')
} else {
e.message = prependMessage + e.message
}
throw e
} finally {
if (debug) {
const duration = (performance.now() - start).toFixed(2)
const depsStr =
Object.keys(orderedDependencies(deps))
.sort()
.map((id) => `\n ${colors.cyan(id)} -> ${colors.dim(deps[id])}`)
.join('') || colors.dim('no dependencies found')
debug(`Scan completed in ${duration}ms: ${depsStr}`)
}
}
})
} finally {
context?.dispose().catch((e) => {
environment.logger.error('Failed to dispose esbuild context', {
error: e,
})
})
}
}
const result = scan()

return {
cancel: async () => {
scanContext.cancelled = true
return esbuildContext.then((context) => context?.cancel())
},
result,
cancel,
result: result.then((res) => res ?? { deps: {}, missing: {} }),
}
}

Expand Down Expand Up @@ -283,10 +274,7 @@ async function prepareEsbuildScanner(
entries: string[],
deps: Record<string, string>,
missing: Record<string, string>,
scanContext: { cancelled: boolean },
): Promise<BuildContext | undefined> {
if (scanContext.cancelled) return

): Promise<BuildContext> {
const plugin = esbuildScanPlugin(environment, deps, missing, entries)

const { plugins = [], ...esbuildOptions } =
Expand Down