Skip to content

Commit

Permalink
feat(ssr): add importer path to error msg when invalid url import occ…
Browse files Browse the repository at this point in the history
…ur (#11606)

Co-authored-by: bluwy <bjornlu.dev@gmail.com>
  • Loading branch information
thomasskk and bluwy committed Feb 18, 2023
1 parent aab4f13 commit 70729c0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
11 changes: 9 additions & 2 deletions packages/vite/src/node/server/transformRequest.ts
Expand Up @@ -5,7 +5,7 @@ import getEtag from 'etag'
import convertSourceMap from 'convert-source-map'
import type { SourceDescription, SourceMap } from 'rollup'
import colors from 'picocolors'
import type { ViteDevServer } from '..'
import type { ModuleNode, ViteDevServer } from '..'
import {
blankReplacer,
cleanUrl,
Expand Down Expand Up @@ -227,8 +227,15 @@ async function loadAndTransform(
`going through the plugin transforms, and therefore should not be ` +
`imported from source code. It can only be referenced via HTML tags.`
: `Does the file exist?`
const importerMod: ModuleNode | undefined = server.moduleGraph.idToModuleMap
.get(id)
?.importers.values()
.next().value
const importer = importerMod?.file || importerMod?.url
const err: any = new Error(
`Failed to load url ${url} (resolved id: ${id}). ${msg}`,
`Failed to load url ${url} (resolved id: ${id})${
importer ? ` in ${importer}` : ''
}. ${msg}`,
)
err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL
throw err
Expand Down
8 changes: 6 additions & 2 deletions packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts
@@ -1,6 +1,8 @@
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import { expect, test } from 'vitest'
import { createServer } from '../../server'
import { normalizePath } from '../../utils'

const root = fileURLToPath(new URL('./', import.meta.url))

Expand All @@ -13,11 +15,13 @@ async function createDevServer() {
test('ssrLoad', async () => {
expect.assertions(1)
const server = await createDevServer()
const moduleRelativePath = '/fixtures/modules/has-invalid-import.js'
const moduleAbsolutePath = normalizePath(path.join(root, moduleRelativePath))
try {
await server.ssrLoadModule('/fixtures/modules/has-invalid-import.js')
await server.ssrLoadModule(moduleRelativePath)
} catch (e) {
expect(e.message).toBe(
'Failed to load url ./non-existent.js (resolved id: ./non-existent.js). Does the file exist?',
`Failed to load url ./non-existent.js (resolved id: ./non-existent.js) in ${moduleAbsolutePath}. Does the file exist?`,
)
}
})
Expand Down

0 comments on commit 70729c0

Please sign in to comment.