Skip to content

Commit

Permalink
fix(ssr): failed ssrLoadModule call throws same error (#7177)
Browse files Browse the repository at this point in the history
Co-authored-by: Rich Harris <hello@rich-harris.dev>
  • Loading branch information
TrickyPi and Rich-Harris committed Apr 30, 2022
1 parent aebaf66 commit 891e7fc
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/vite/src/node/server/moduleGraph.ts
Expand Up @@ -33,6 +33,7 @@ export class ModuleNode {
transformResult: TransformResult | null = null
ssrTransformResult: TransformResult | null = null
ssrModule: Record<string, any> | null = null
ssrError: Error | null = null
lastHMRTimestamp = 0
lastInvalidationTimestamp = 0

Expand Down
@@ -0,0 +1,2 @@
export const bad = 1
throw new Error('it is an expected error')
29 changes: 29 additions & 0 deletions packages/vite/src/node/ssr/__tests__/ssrModuleLoader.spec.ts
@@ -0,0 +1,29 @@
import { resolve } from 'path'
import { createServer } from '../../index'

const badjs = resolve(__dirname, './fixtures/ssrModuleLoader-bad.js')
const THROW_MESSAGE = 'it is an expected error'

test('always throw error when evaluating an wrong SSR module', async () => {
const viteServer = await createServer()
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
const expectedErrors = []
for (const i of [0, 1]) {
try {
await viteServer.ssrLoadModule(badjs)
} catch (e) {
expectedErrors.push(e)
}
}
await viteServer.close()
expect(expectedErrors).toHaveLength(2)
expect(expectedErrors[0]).toBe(expectedErrors[1])
expectedErrors.forEach((error) => {
expect(error?.message).toContain(THROW_MESSAGE)
})
expect(spy).toBeCalledTimes(1)
const [firstParameter] = spy.mock.calls[0]
expect(firstParameter).toContain('Error when evaluating SSR module')
expect(firstParameter).toContain(THROW_MESSAGE)
spy.mockClear()
})
5 changes: 5 additions & 0 deletions packages/vite/src/node/ssr/ssrModuleLoader.ts
Expand Up @@ -77,6 +77,10 @@ async function instantiateModule(
const { moduleGraph } = server
const mod = await moduleGraph.ensureEntryFromUrl(url, true)

if (mod.ssrError) {
throw mod.ssrError
}

if (mod.ssrModule) {
return mod.ssrModule
}
Expand Down Expand Up @@ -202,6 +206,7 @@ async function instantiateModule(
ssrExportAll
)
} catch (e) {
mod.ssrError = e
if (e.stack && fixStacktrace !== false) {
const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph)
rebindErrorStacktrace(e, stacktrace)
Expand Down

0 comments on commit 891e7fc

Please sign in to comment.