From 004a12f54ee29b6cdd57e5a5a07510b5ffba9873 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 | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 892d27fec1e72d..b4fddede601cfd 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,22 @@ 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) + } + searchParams.sort() + const search = Array.from(searchParams.entries(), ([key, value]) => + value !== '' ? `${key}=${value}` : key + ).join('&') + return `${pathname}?${search}${hash || ''}` } const timestampRE = /\bt=\d{13}&?\b/