Skip to content
This repository was archived by the owner on Mar 19, 2026. It is now read-only.

Commit edfd293

Browse files
committed
fix: importing an optional peer dep should throw an runtime error
1 parent bf77840 commit edfd293

2 files changed

Lines changed: 5 additions & 13 deletions

File tree

packages/vite/src/node/plugins/resolve.ts

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -772,14 +772,7 @@ export function resolvePlugin(
772772
}
773773
}
774774
if (id.startsWith(optionalPeerDepId)) {
775-
const [, peerDep, parentDep, isRequire] = id.split(':')
776-
// rollup + @rollup/plugin-commonjs hoists dynamic `require`s by default
777-
// If we add a `throw` statement, it will be injected to the top-level and break the whole bundle
778-
// Instead, we mock the module for now
779-
// This can be fixed when we migrate to rolldown
780-
if (isRequire === 'true' && isProduction) {
781-
return 'export default {}'
782-
}
775+
const [, peerDep, parentDep] = id.split(':')
783776
return (
784777
'export default {};' +
785778
`throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}".${isProduction ? '' : ' Is it installed?'}\`)`
@@ -1048,7 +1041,7 @@ export function tryNodeResolve(
10481041
mainPkg.peerDependenciesMeta?.[pkgName]?.optional
10491042
) {
10501043
return {
1051-
id: `${optionalPeerDepId}:${id}:${mainPkg.name}:${!!options.isRequire}`,
1044+
id: `${optionalPeerDepId}:${id}:${mainPkg.name}`,
10521045
}
10531046
}
10541047
}

playground/optimize-deps/__tests__/optimize-deps.spec.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,9 @@ test('dep with optional peer dep (cjs)', async () => {
161161
await expectWithRetry(() =>
162162
page.textContent('.dep-with-optional-peer-dep-cjs'),
163163
).toMatch(`[success]`)
164-
// FIXME
165-
// await expectWithRetry(() =>
166-
// page.textContent('.dep-with-optional-peer-dep-cjs-error'),
167-
// ).toMatch(`[success]`)
164+
await expectWithRetry(() =>
165+
page.textContent('.dep-with-optional-peer-dep-cjs-error'),
166+
).toMatch(`[success]`)
168167
})
169168

170169
test('dep with css import', async () => {

0 commit comments

Comments
 (0)