Skip to content

Commit b53667a

Browse files
authored
fix: importing an optional peer dep should throw an runtime error (#167)
1 parent 6f8287b commit b53667a

File tree

2 files changed

+5
-13
lines changed

2 files changed

+5
-13
lines changed

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

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -812,14 +812,7 @@ export function resolvePlugin(
812812
}
813813
}
814814
if (id.startsWith(optionalPeerDepId)) {
815-
const [, peerDep, parentDep, isRequire] = id.split(':')
816-
// rollup + @rollup/plugin-commonjs hoists dynamic `require`s by default
817-
// If we add a `throw` statement, it will be injected to the top-level and break the whole bundle
818-
// Instead, we mock the module for now
819-
// This can be fixed when we migrate to rolldown
820-
if (isRequire === 'true' && isProduction) {
821-
return 'export default {}'
822-
}
815+
const [, peerDep, parentDep] = id.split(':')
823816
return (
824817
'export default {};' +
825818
`throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}".${isProduction ? '' : ' Is it installed?'}\`)`
@@ -1088,7 +1081,7 @@ export function tryNodeResolve(
10881081
mainPkg.peerDependenciesMeta?.[pkgName]?.optional
10891082
) {
10901083
return {
1091-
id: `${optionalPeerDepId}:${id}:${mainPkg.name}:${!!options.isRequire}`,
1084+
id: `${optionalPeerDepId}:${id}:${mainPkg.name}`,
10921085
}
10931086
}
10941087
}

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,10 +142,9 @@ test('dep with optional peer dep (cjs)', async () => {
142142
await expect
143143
.poll(() => page.textContent('.dep-with-optional-peer-dep-cjs'))
144144
.toMatch(`[success]`)
145-
// FIXME
146-
// await expect
147-
// .poll(() => page.textContent('.dep-with-optional-peer-dep-cjs-error'))
148-
// .toMatch(`[success]`)
145+
await expect
146+
.poll(() => page.textContent('.dep-with-optional-peer-dep-cjs-error'))
147+
.toMatch(`[success]`)
149148
})
150149

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

0 commit comments

Comments
 (0)