From 4f29dee1700996159956de4d458aba7f0fc2def9 Mon Sep 17 00:00:00 2001 From: GrygrFlzr Date: Tue, 9 Mar 2021 00:11:50 +0700 Subject: [PATCH] fix: Improve injectQuery path handling close #2422 --- packages/vite/src/node/utils.ts | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 892d27fec1e72d..3d50565f77bc0b 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -3,7 +3,7 @@ import chalk from 'chalk' import fs from 'fs' import os from 'os' import path from 'path' -import { parse as parseUrl } from 'url' +import { pathToFileURL, URL, URLSearchParams } from 'url' import { FS_PREFIX, DEFAULT_EXTENSIONS, VALID_ID_PREFIX } from './constants' import resolve from 'resolve' import builtins from 'builtin-modules' @@ -119,10 +119,21 @@ export function removeImportQuery(url: string) { } export function injectQuery(url: string, queryToInject: string) { - const { pathname, search, hash } = parseUrl(url) - return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${ - hash || '' - }` + let resolvedUrl = new URL(url, 'relative:///') + if (resolvedUrl.protocol !== 'relative:') { + resolvedUrl = pathToFileURL(url) + } + let { protocol, pathname, searchParams, hash } = resolvedUrl + if (protocol === 'file:') { + pathname = pathname.slice(1) + } + for (const [key, value] of new URLSearchParams(queryToInject).entries()) { + searchParams.append(key, value) + } + const search = Array.from(searchParams.entries(), ([key, value]) => + value !== '' ? `${key}=${value}` : key + ).join('&') + return `${pathname}?${search}${hash || ''}` } const timestampRE = /\bt=\d{13}&?\b/