Skip to content

Commit 891e7fc

Browse files
fix(ssr): failed ssrLoadModule call throws same error (#7177)
Co-authored-by: Rich Harris <[email protected]>
1 parent aebaf66 commit 891e7fc

File tree

4 files changed

+37
-0
lines changed

4 files changed

+37
-0
lines changed

packages/vite/src/node/server/moduleGraph.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export class ModuleNode {
3333
transformResult: TransformResult | null = null
3434
ssrTransformResult: TransformResult | null = null
3535
ssrModule: Record<string, any> | null = null
36+
ssrError: Error | null = null
3637
lastHMRTimestamp = 0
3738
lastInvalidationTimestamp = 0
3839

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const bad = 1
2+
throw new Error('it is an expected error')
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { resolve } from 'path'
2+
import { createServer } from '../../index'
3+
4+
const badjs = resolve(__dirname, './fixtures/ssrModuleLoader-bad.js')
5+
const THROW_MESSAGE = 'it is an expected error'
6+
7+
test('always throw error when evaluating an wrong SSR module', async () => {
8+
const viteServer = await createServer()
9+
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
10+
const expectedErrors = []
11+
for (const i of [0, 1]) {
12+
try {
13+
await viteServer.ssrLoadModule(badjs)
14+
} catch (e) {
15+
expectedErrors.push(e)
16+
}
17+
}
18+
await viteServer.close()
19+
expect(expectedErrors).toHaveLength(2)
20+
expect(expectedErrors[0]).toBe(expectedErrors[1])
21+
expectedErrors.forEach((error) => {
22+
expect(error?.message).toContain(THROW_MESSAGE)
23+
})
24+
expect(spy).toBeCalledTimes(1)
25+
const [firstParameter] = spy.mock.calls[0]
26+
expect(firstParameter).toContain('Error when evaluating SSR module')
27+
expect(firstParameter).toContain(THROW_MESSAGE)
28+
spy.mockClear()
29+
})

packages/vite/src/node/ssr/ssrModuleLoader.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ async function instantiateModule(
7777
const { moduleGraph } = server
7878
const mod = await moduleGraph.ensureEntryFromUrl(url, true)
7979

80+
if (mod.ssrError) {
81+
throw mod.ssrError
82+
}
83+
8084
if (mod.ssrModule) {
8185
return mod.ssrModule
8286
}
@@ -202,6 +206,7 @@ async function instantiateModule(
202206
ssrExportAll
203207
)
204208
} catch (e) {
209+
mod.ssrError = e
205210
if (e.stack && fixStacktrace !== false) {
206211
const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph)
207212
rebindErrorStacktrace(e, stacktrace)

0 commit comments

Comments
 (0)