From 70729c00a5e846643b163ea7c703332894c70af0 Mon Sep 17 00:00:00 2001 From: thomasskk <77022096+thomasskk@users.noreply.github.com> Date: Sat, 18 Feb 2023 12:21:15 +0100 Subject: [PATCH] feat(ssr): add importer path to error msg when invalid url import occur (#11606) Co-authored-by: bluwy --- packages/vite/src/node/server/transformRequest.ts | 11 +++++++++-- .../vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts | 8 ++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/node/server/transformRequest.ts b/packages/vite/src/node/server/transformRequest.ts index fb64c190cce7f6..a75d78c0b6af5e 100644 --- a/packages/vite/src/node/server/transformRequest.ts +++ b/packages/vite/src/node/server/transformRequest.ts @@ -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, @@ -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 diff --git a/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts index 8b81372a2697dd..13d51db0941e19 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts +++ b/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)) @@ -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?`, ) } })